Class: OnyxCord::Bot

Inherits:
Object
  • Object
show all
Includes:
ApplicationCommands, Awaits, Cogs, Extensions, Invites, Messaging, OAuth, Presence, Runtime, VoiceControl, Cache, EventContainer, Internal::EventBus
Defined in:
lib/onyxcord/bot.rb,
lib/onyxcord/cogs/bot.rb,
lib/onyxcord/core/bot/oauth.rb,
lib/onyxcord/core/bot/voice.rb,
lib/onyxcord/cogs/extensions.rb,
lib/onyxcord/core/bot/awaits.rb,
lib/onyxcord/core/bot/invites.rb,
lib/onyxcord/core/bot/runtime.rb,
lib/onyxcord/core/bot/presence.rb,
lib/onyxcord/core/bot/messaging.rb,
lib/onyxcord/core/bot/application_commands.rb

Overview

Represents a Discord bot, including servers, users, etc.

Direct Known Subclasses

Commands::Bot

Defined Under Namespace

Modules: ApplicationCommands, Awaits, Cogs, Extensions, Invites, Messaging, OAuth, Presence, Runtime, VoiceControl

Constant Summary

Constants included from Cache

Cache::CACHE_STORES

Instance Attribute Summary collapse

Attributes included from Extensions

#extensions

Attributes included from Cogs

#cogs

Attributes included from VoiceControl

#voices

Instance Method Summary collapse

Methods included from Extensions

#load_extension, #load_extensions, #reload_extension, #unload_extension

Methods included from Cogs

#add_cog, #get_cog, #remove_cog

Methods included from ApplicationCommands

#application_command_permissions, #application_command_registry, #application_emoji, #application_emojis, #bulk_overwrite_global_application_commands, #bulk_overwrite_guild_application_commands, #commands, #create_application_emoji, #delete_application_command, #delete_application_emoji, #edit_application_command, #edit_application_command_permissions, #edit_application_emoji, #get_application_command, #get_application_commands, #message_command, #register_application_command, #slash, #sync_application_commands!, #user_command

Methods included from Awaits

#add_await, #add_await!, #debug, #dispatch, #ignore_user, #ignored?, #log_exception, #raise_heartbeat_event, #unignore_user

Methods included from Presence

#competing=, #dnd, #game=, #idle, #invisible, #listening=, #online, #stream, #update_status, #watching=

Methods included from OAuth

#create_oauth_application, #update_oauth_application

Methods included from Messaging

#add_thread_member, #join_thread, #leave_thread, #parse_mention, #parse_mentions, #prune_empty_groups, #remove_thread_member, #send_file, #send_message, #send_temporary_message

Methods included from VoiceControl

#voice, #voice_connect, #voice_destroy

Methods included from Invites

#accept_invite, #delete_invite, #invite_url

Methods included from Runtime

#connected?, #debug=, #join, #latency, #mode=, #run, #run_forever, #runtime_stats, #stop, #suppress_ready_debug

Methods included from Internal::EventBus

#call_raw_handler, #dispatch_packet, #dispatch_raw_packet, #handle_dispatch, #notify_raw_ready

Methods included from Events

#added_members, matches_all

Methods included from Cache

#cache_enabled?, #cache_stats, #channel, #ensure_channel, #ensure_server, #ensure_thread_member, #ensure_user, #fetch_voice_regions, #find_channel, #find_user, #init_cache, #invite, #member, #pm_channel, #prune_cache!, #request_chunks, #resolve_invite_code, #server, #server_preview, #user, #voice_regions

Methods included from EventContainer

#add_handler, #application_command, #application_command_permissions_update, #audit_log_entry, #autocomplete, #await, #button, #channel_create, #channel_delete, #channel_pins_update, #channel_recipient_add, #channel_recipient_remove, #channel_select, #channel_update, class_from_string, #clear!, #disconnected, event_class, handler_class, #heartbeat, #include_events, #integration_create, #integration_delete, #integration_update, #interaction_create, #invite_create, #invite_delete, #member_join, #member_leave, #member_update, #mention, #mentionable_select, #message, #message_delete, #message_edit, #message_update, #modal_submit, #playing, #pm, #poll_vote_add, #poll_vote_remove, #presence, #raw, #reaction_add, #reaction_remove, #reaction_remove_all, #reaction_remove_emoji, #ready, #remove_application_command_handler, #remove_handler, #role_select, #scheduled_event_create, #scheduled_event_delete, #scheduled_event_update, #scheduled_event_user_add, #scheduled_event_user_remove, #server_create, #server_delete, #server_emoji, #server_emoji_create, #server_emoji_delete, #server_emoji_update, #server_role_create, #server_role_delete, #server_role_update, #server_update, #string_select, #typing, #unknown, #user_ban, #user_select, #user_unban, #voice_server_update, #voice_state_update, #webhook_update

Constructor Details

#initialize(log_mode: :normal, token: nil, client_id: nil, type: nil, name: '', fancy_log: false, suppress_ready: false, parse_self: false, shard_id: nil, num_shards: nil, redact_token: true, ignore_bots: false, compress_mode: :large, intents: :minimal, mode: nil, cache: nil, event_executor: nil, event_workers: nil, event_queue_size: nil) ⇒ Bot

Makes a new bot with the given authentication data. It will be ready to be added event handlers to and can eventually be run with OnyxCord::Bot::Runtime#run.

As support for logging in using username and password has been removed in version 3.0.0, only a token login is possible. Be sure to specify the type parameter as :user if you're logging in as a user.

Simply creating a bot won't be enough to start sending messages etc. with, only a limited set of methods can be used after logging in. If you want to do something when the bot has connected successfully, either do it in the EventContainer#ready event, or use the OnyxCord::Bot::Runtime#run method with the :async parameter and do the processing after that.

Parameters:

  • log_mode (Symbol) (defaults to: :normal)

    The mode this bot should use for logging. See Logger#mode= for a list of modes.

  • token (String) (defaults to: nil)

    The token that should be used to log in. If your bot is a bot account, you have to specify this. If you're logging in as a user, make sure to also set the account type to :user so onyxcord doesn't think you're trying to log in as a bot.

  • client_id (Integer) (defaults to: nil)

    If you're logging in as a bot, the bot's client ID. This is optional, and may be fetched from the API by calling #bot_application (see Application).

  • type (Symbol) (defaults to: nil)

    This parameter lets you manually overwrite the account type. This needs to be set when logging in as a user, otherwise onyxcord will treat you as a bot account. Valid values are :user and :bot.

  • name (String) (defaults to: '')

    Your bot's name. This will be sent to Discord with any API requests, who will use this to trace the source of excessive API requests; it's recommended to set this to something if you make bots that many people will host on their servers separately.

  • fancy_log (true, false) (defaults to: false)

    Whether the output log should be made extra fancy using ANSI escape codes. (Your terminal may not support this.)

  • suppress_ready (true, false) (defaults to: false)

    Whether the READY packet should be exempt from being printed to console. Useful for very large bots running in debug or verbose log_mode.

  • parse_self (true, false) (defaults to: false)

    Whether the bot should react on its own messages. It's best to turn this off unless you really need this so you don't inadvertently create infinite loops.

  • shard_id (Integer) (defaults to: nil)

    The number of the shard this bot should handle. See https://github.com/discord/discord-api-docs/issues/17 for how to do sharding.

  • num_shards (Integer) (defaults to: nil)

    The total number of shards that should be running. See https://github.com/discord/discord-api-docs/issues/17 for how to do sharding.

  • redact_token (true, false) (defaults to: true)

    Whether the bot should redact the token in logs. Default is true.

  • ignore_bots (true, false) (defaults to: false)

    Whether the bot should ignore bot accounts or not. Default is false.

  • compress_mode (:none, :large, :stream) (defaults to: :large)

    Sets which compression mode should be used when connecting to Discord's gateway. :none will request that no payloads are received compressed (not recommended for production bots). :large will request that large payloads are received compressed. :stream will request that all data be received in a continuous compressed stream.

  • intents (:all, :unprivileged, Array<Symbol>, :none, Integer) (defaults to: :minimal)

    Gateway intents that this bot requires. :all will request all intents. :unprivileged will request only intents that are not defined as "Privileged". :none will request no intents. An array of symbols will request only those intents specified. An integer value will request exactly all the intents specified in the bitwise value.

See Also:



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/onyxcord/bot.rb', line 108

def initialize(
  log_mode: :normal,
  token: nil, client_id: nil,
  type: nil, name: '', fancy_log: false, suppress_ready: false, parse_self: false,
  shard_id: nil, num_shards: nil, redact_token: true, ignore_bots: false,
  compress_mode: :large, intents: :minimal,
  mode: nil, cache: nil, event_executor: nil, event_workers: nil, event_queue_size: nil
)
  config = OnyxCord.configuration
  @mode = config.normalize_mode(mode)
  @cache_policy = config.normalize_cache(cache)
  executor_type = config.normalize_event_executor(event_executor)
  executor_workers = config.normalize_event_workers(event_workers)
  executor_queue_size = config.normalize_event_queue_size(event_queue_size)

  LOGGER.mode = log_mode
  @redact_token = redact_token
  LOGGER.token = token if @redact_token

  @should_parse_self = parse_self

  @client_id = client_id

  @type = type || :bot
  @name = name

  @shard_key = num_shards ? [shard_id, num_shards] : nil

  LOGGER.fancy = fancy_log
  @prevent_ready = suppress_ready

  @compress_mode = compress_mode

  raise 'Token string is empty or nil' if token.nil? || token.empty?

  @intents = case intents
             when :all
               ALL_INTENTS
             when :unprivileged
               UNPRIVILEGED_INTENTS
             when :minimal
               MINIMAL_INTENTS
             when :none
               NO_INTENTS
             else
               calculate_intents(intents)
             end

  @token = process_token(@type, token)
  @gateway = Gateway::Client.new(self, @token, @shard_key, @compress_mode, @intents)

  init_cache

  @voices = {}
  @should_connect_to_voice = {}

  @ignored_ids = Set.new
  @ignore_bots = ignore_bots

  @current_thread = 0
  @current_thread_mutex = Mutex.new
  @event_executor = Internal::EventExecutor.build(executor_type, workers: executor_workers, queue_size: executor_queue_size)
  @event_threads = @event_executor.threads

  @status = :online

  @application_commands = {}
  @request_members_rl = {}
  @cogs = {}
end

Instance Attribute Details

#awaitsHash<Symbol => Await> (readonly)

Returns the list of registered Awaits.

Returns:

  • (Hash<Symbol => Await>)

    the list of registered Awaits.



37
38
39
# File 'lib/onyxcord/bot.rb', line 37

def awaits
  @awaits
end

#cache_policyHash (readonly)

Returns the normalized cache policy for this bot.

Returns:

  • (Hash)

    the normalized cache policy for this bot.



48
49
50
# File 'lib/onyxcord/bot.rb', line 48

def cache_policy
  @cache_policy
end

#event_executorInternal::EventExecutor::Inline, ... (readonly)



51
52
53
# File 'lib/onyxcord/bot.rb', line 51

def event_executor
  @event_executor
end

#event_threadsArray<Thread> (readonly)

The list of currently running threads used to parse and call events. The threads will have a local variable :onyxcord_name in the format of et-1234, where "et" stands for "event thread" and the number is a continually incrementing number representing how many events were executed before.

Returns:

  • (Array<Thread>)

    The threads.



23
24
25
# File 'lib/onyxcord/bot.rb', line 23

def event_threads
  @event_threads
end

#gatewayGateway (readonly)

The gateway connection is an internal detail that is useless to most people. It is however essential while debugging or developing onyxcord itself, or while writing very custom bots.

Returns:



42
43
44
# File 'lib/onyxcord/bot.rb', line 42

def gateway
  @gateway
end

#mode:raw, ... (readonly)

Returns the dispatch mode used by this bot.

Returns:

  • (:raw, :hybrid, :object)

    the dispatch mode used by this bot.



45
46
47
# File 'lib/onyxcord/bot.rb', line 45

def mode
  @mode
end

#nameString

The bot's name which onyxcord sends to Discord when making any request, so Discord can identify bots with the same codebase. Not required but I recommend setting it anyway.

Returns:

  • (String)

    The bot's name.



31
32
33
# File 'lib/onyxcord/bot.rb', line 31

def name
  @name
end

#shard_keyArray(Integer, Integer) (readonly)

Returns the current shard key.

Returns:



34
35
36
# File 'lib/onyxcord/bot.rb', line 34

def shard_key
  @shard_key
end

#should_parse_selftrue, false

Returns whether or not the bot should parse its own messages. Off by default.

Returns:

  • (true, false)

    whether or not the bot should parse its own messages. Off by default.



26
27
28
# File 'lib/onyxcord/bot.rb', line 26

def should_parse_self
  @should_parse_self
end

Instance Method Details

#bot_applicationApplication Also known as: bot_app, application

The bot's OAuth application.

Returns:



251
252
253
254
# File 'lib/onyxcord/bot.rb', line 251

def bot_application
  response = REST.oauth_application(token)
  Application.new(OnyxCord::Internal::JSON.parse(response), self)
end

#emoji(id) ⇒ Emoji? #emojiArray<Emoji> Also known as: emojis, all_emoji

Overloads:

  • #emoji(id) ⇒ Emoji?

    Return an emoji by its ID

    Parameters:

    Returns:

    • (Emoji, nil)

      the emoji object. nil if the emoji was not found.

  • #emojiArray<Emoji>

    The list of emoji the bot can use.

    Returns:

    • (Array<Emoji>)

      the emoji available.



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/onyxcord/bot.rb', line 210

def emoji(id = nil)
  if (id = id&.resolve_id)
    @servers.each_value do |server|
      emoji = server.emojis[id]
      return emoji if emoji
    end
  else
    hash = {}
    @servers.each_value do |server|
      hash.merge!(server.emojis)
    end

    hash
  end
end

#find_emoji(name) ⇒ GlobalEmoji?

Finds an emoji by its name.

Parameters:

  • name (String)

    The emoji name that should be resolved.

Returns:

  • (GlobalEmoji, nil)

    the emoji identified by the name, or nil if it couldn't be found.



232
233
234
235
# File 'lib/onyxcord/bot.rb', line 232

def find_emoji(name)
  LOGGER.out("Resolving emoji #{name}")
  emoji.values.find { |element| element.name == name }
end

#profileProfile Also known as: bot_user

The bot's user profile. This special user object can be used to edit user data like the current username (see Profile#username=).

Returns:

  • (Profile)

    The bot's profile that can be used to edit data.



240
241
242
243
244
245
# File 'lib/onyxcord/bot.rb', line 240

def profile
  return @profile if @profile

  response = OnyxCord::REST::User.profile(@token)
  @profile = Profile.new(OnyxCord::Internal::JSON.parse(response), self)
end

#raw_tokenString

Returns the raw token, without any prefix.

Returns:

  • (String)

    the raw token, without any prefix

See Also:



276
277
278
# File 'lib/onyxcord/bot.rb', line 276

def raw_token
  @token.split(' ').last
end

#role_connection_metadata_recordsArray<RoleConnectionMetadata>

Get the role connection metadata records associated with this application.

Returns:



261
262
263
264
# File 'lib/onyxcord/bot.rb', line 261

def 
  response = REST::Application.(token, @client_id)
  OnyxCord::Internal::JSON.parse(response).map { |role_connection| RoleConnectionMetadata.new(role_connection, self) }
end

#serversHash<Integer => Server>

The list of servers the bot is currently in.

Returns:



189
190
191
192
193
# File 'lib/onyxcord/bot.rb', line 189

def servers
  gateway_check
  unavailable_servers_check
  @servers
end

#thread_membersHash<Integer => Hash<Integer => Hash<String => Object>>]

The list of members in threads the bot can see.

Returns:

  • (Hash<Integer => Hash<Integer => Hash<String => Object>>])

    Hash<Integer => Hash<Integer => Hash<String => Object>>]



197
198
199
200
201
# File 'lib/onyxcord/bot.rb', line 197

def thread_members
  gateway_check
  unavailable_servers_check
  @thread_members
end

#tokenString

The Discord API token received when logging in. Useful to explicitly call API methods.

Returns:



269
270
271
272
# File 'lib/onyxcord/bot.rb', line 269

def token
  REST.bot_name = @name
  @token
end

#usersHash<Integer => User>

The list of users the bot shares a server with.

Returns:



181
182
183
184
185
# File 'lib/onyxcord/bot.rb', line 181

def users
  gateway_check
  unavailable_servers_check
  @users
end