idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
2,000 | def load_models ( app ) app . config . paths [ "app/models" ] . expanded . each do | path | preload = :: Mongoid . preload_models if preload . resizable? files = preload . map { | model | "#{path}/#{model.underscore}.rb" } else files = Dir . glob ( "#{path}/**/*.rb" ) end files . sort . each do | file | load_model ( file . gsub ( "#{path}/" , "" ) . gsub ( ".rb" , "" ) ) end end end | Use the application configuration to get every model and require it so that indexing and inheritance work in both development and production with the same results . |
2,001 | def load_model ( file ) begin require_dependency ( file ) rescue Exception => e Logger . new ( $stdout ) . warn ( e . message ) end end | I don t want to mock out kernel for unit testing purposes so added this method as a convenience . |
2,002 | def apply_default ( name ) unless attributes . key? ( name ) if field = fields [ name ] default = field . eval_default ( self ) unless default . nil? || field . lazy? attribute_will_change! ( name ) attributes [ name ] = default end end end end | Applies a single default value for the given name . |
2,003 | def post_process_persist ( result , options = { } ) post_persist unless result == false errors . clear unless performing_validations? ( options ) true end | Post process the persistence operation . |
2,004 | def process_atomic_operations ( operations ) operations . each do | field , value | access = database_field_name ( field ) yield ( access , value ) remove_change ( access ) unless executing_atomically? end end | Process the atomic operations - this handles the common behavior of iterating through each op getting the aliased field name and removing appropriate dirty changes . |
2,005 | def persist_or_delay_atomic_operation ( operation ) if executing_atomically? operation . each do | ( name , hash ) | @atomic_context [ name ] ||= { } @atomic_context [ name ] . merge! ( hash ) end else persist_atomic_operations ( operation ) end end | If we are in an atomically block add the operations to the delayed group otherwise persist immediately . |
2,006 | def persist_atomic_operations ( operations ) if persisted? && operations && ! operations . empty? selector = atomic_selector _root . collection . find ( selector ) . update_one ( positionally ( selector , operations ) , session : _session ) end end | Persist the atomic operations . |
2,007 | def serializable_hash ( options = nil ) options ||= { } attrs = { } names = field_names ( options ) method_names = Array . wrap ( options [ :methods ] ) . map do | name | name . to_s if respond_to? ( name ) end . compact ( names + method_names ) . each do | name | without_autobuild do serialize_attribute ( attrs , name , names , options ) end end serialize_relations ( attrs , options ) if options [ :include ] attrs end | Gets the document as a serializable hash used by ActiveModel s JSON serializer . |
2,008 | def field_names ( options ) names = ( as_attributes . keys + attribute_names ) . uniq . sort only = Array . wrap ( options [ :only ] ) . map ( & :to_s ) except = Array . wrap ( options [ :except ] ) . map ( & :to_s ) except |= [ '_type' ] unless Mongoid . include_type_for_serialization if ! only . empty? names &= only elsif ! except . empty? names -= except end names end | Get the names of all fields that will be serialized . |
2,009 | def serialize_attribute ( attrs , name , names , options ) if relations . key? ( name ) value = send ( name ) attrs [ name ] = value ? value . serializable_hash ( options ) : nil elsif names . include? ( name ) && ! fields . key? ( name ) attrs [ name ] = read_raw_attribute ( name ) elsif ! attribute_missing? ( name ) attrs [ name ] = send ( name ) end end | Serialize a single attribute . Handles associations fields and dynamic attributes . |
2,010 | def serialize_relations ( attributes = { } , options = { } ) inclusions = options [ :include ] relation_names ( inclusions ) . each do | name | association = relations [ name . to_s ] if association && relation = send ( association . name ) attributes [ association . name . to_s ] = relation . serializable_hash ( relation_options ( inclusions , options , name ) ) end end end | For each of the provided include options get the association needed and provide it in the hash . |
2,011 | def relation_names ( inclusions ) inclusions . is_a? ( Hash ) ? inclusions . keys : Array . wrap ( inclusions ) end | Since the inclusions can be a hash symbol or array of symbols this is provided as a convenience to parse out the names . |
2,012 | def relation_options ( inclusions , options , name ) if inclusions . is_a? ( Hash ) inclusions [ name ] else { except : options [ :except ] , only : options [ :only ] } end end | Since the inclusions can be a hash symbol or array of symbols this is provided as a convenience to parse out the options . |
2,013 | def current_scope ( klass = nil ) if klass && Thread . current [ CURRENT_SCOPE_KEY ] . respond_to? ( :keys ) Thread . current [ CURRENT_SCOPE_KEY ] [ Thread . current [ CURRENT_SCOPE_KEY ] . keys . find { | k | k <= klass } ] else Thread . current [ CURRENT_SCOPE_KEY ] end end | Get the current Mongoid scope . |
2,014 | def set_current_scope ( scope , klass ) if scope . nil? if Thread . current [ CURRENT_SCOPE_KEY ] Thread . current [ CURRENT_SCOPE_KEY ] . delete ( klass ) Thread . current [ CURRENT_SCOPE_KEY ] = nil if Thread . current [ CURRENT_SCOPE_KEY ] . empty? end else Thread . current [ CURRENT_SCOPE_KEY ] ||= { } Thread . current [ CURRENT_SCOPE_KEY ] [ klass ] = scope end end | Set the current Mongoid scope . Safe for multi - model scope chaining . |
2,015 | def apply_default_scoping if default_scoping default_scoping . call . selector . each do | field , value | attributes [ field ] = value unless value . respond_to? ( :each ) end end end | Apply the default scoping to the attributes of the document as long as they are not complex queries . |
2,016 | def read_attribute_for_validation ( attr ) attribute = database_field_name ( attr ) if relations . key? ( attribute ) begin_validate relation = without_autobuild { send ( attr ) } exit_validate relation . do_or_do_not ( :in_memory ) || relation elsif fields [ attribute ] . try ( :localized? ) attributes [ attribute ] else send ( attr ) end end | Overrides the default ActiveModel behavior since we need to handle validations of associations slightly different than just calling the getter . |
2,017 | def collect_children children = [ ] embedded_relations . each_pair do | name , association | without_autobuild do child = send ( name ) Array . wrap ( child ) . each do | doc | children . push ( doc ) children . concat ( doc . _children ) end if child end end children end | Collect all the children of this document . |
2,018 | def remove_child ( child ) name = child . association_name if child . embedded_one? remove_ivar ( name ) else relation = send ( name ) relation . send ( :delete_one , child ) end end | Remove a child document from this parent . If an embeds one then set to nil otherwise remove from the embeds many . |
2,019 | def reset_persisted_children _children . each do | child | child . move_changes child . new_record = false end _reset_memoized_children! end | After children are persisted we can call this to move all their changes and flag them as persisted in one call . |
2,020 | def becomes ( klass ) unless klass . include? ( Mongoid :: Document ) raise ArgumentError , "A class which includes Mongoid::Document is expected" end became = klass . new ( clone_document ) became . _id = _id became . instance_variable_set ( :@changed_attributes , changed_attributes ) became . instance_variable_set ( :@errors , ActiveModel :: Errors . new ( became ) ) became . errors . instance_variable_set ( :@messages , errors . instance_variable_get ( :@messages ) ) became . instance_variable_set ( :@new_record , new_record? ) became . instance_variable_set ( :@destroyed , destroyed? ) became . changed_attributes [ "_type" ] = self . class . to_s became . _type = klass . to_s embedded_relations . each_pair do | name , meta | without_autobuild do relation = became . __send__ ( name ) Array . wrap ( relation ) . each do | r | r . instance_variable_set ( :@new_record , new_record? ) end end end became end | Returns an instance of the specified class with the attributes errors and embedded documents of the current document . |
2,021 | def reload_relations relations . each_pair do | name , meta | if instance_variable_defined? ( "@_#{name}" ) if _parent . nil? || instance_variable_get ( "@_#{name}" ) != _parent remove_instance_variable ( "@_#{name}" ) end end end end | Convenience method for iterating through the loaded associations and reloading them . |
2,022 | def inspect_fields fields . map do | name , field | unless name == "_id" as = field . options [ :as ] "#{name}#{as ? "(#{as})" : nil}: #{@attributes[name].inspect}" end end . compact end | Get an array of inspected fields for the document . |
2,023 | def run_callbacks ( kind , * args , & block ) cascadable_children ( kind ) . each do | child | if child . run_callbacks ( child_callback_type ( kind , child ) , * args ) == false return false end end callback_executable? ( kind ) ? super ( kind , * args , & block ) : true end | Run the callbacks for the document . This overrides active support s functionality to cascade callbacks to embedded documents that have been flagged as such . |
2,024 | def cascadable_children ( kind , children = Set . new ) embedded_relations . each_pair do | name , association | next unless association . cascading_callbacks? without_autobuild do delayed_pulls = delayed_atomic_pulls [ name ] delayed_unsets = delayed_atomic_unsets [ name ] children . merge ( delayed_pulls ) if delayed_pulls children . merge ( delayed_unsets ) if delayed_unsets relation = send ( name ) Array . wrap ( relation ) . each do | child | next if children . include? ( child ) children . add ( child ) if cascadable_child? ( kind , child , association ) child . send ( :cascadable_children , kind , children ) end end end children . to_a end | Get all the child embedded documents that are flagged as cascadable . |
2,025 | def cascadable_child? ( kind , child , association ) return false if kind == :initialize || kind == :find || kind == :touch return false if kind == :validate && association . validate? child . callback_executable? ( kind ) ? child . in_callback_state? ( kind ) : false end | Determine if the child should fire the callback . |
2,026 | def connect_to ( name , options = { read : { mode : :primary } } ) self . clients = { default : { database : name , hosts : [ "localhost:27017" ] , options : options } } end | Connect to the provided database name on the default client . |
2,027 | def load! ( path , environment = nil ) settings = Environment . load_yaml ( path , environment ) if settings . present? Clients . disconnect Clients . clear load_configuration ( settings ) end settings end | Load the settings from a compliant mongoid . yml file . This can be used for easy setup with frameworks other than Rails . |
2,028 | def register_model ( klass ) LOCK . synchronize do models . push ( klass ) unless models . include? ( klass ) end end | Register a model in the application with Mongoid . |
2,029 | def load_configuration ( settings ) configuration = settings . with_indifferent_access self . options = configuration [ :options ] self . clients = configuration [ :clients ] set_log_levels end | From a hash of settings load all the configuration . |
2,030 | def truncate! Clients . default . database . collections . each do | collection | collection . find . delete_many end and true end | Truncate all data in all collections but not the indexes . |
2,031 | def options = ( options ) if options options . each_pair do | option , value | Validators :: Option . validate ( option ) send ( "#{option}=" , value ) end end end | Set the configuration options . Will validate each one individually . |
2,032 | def deny_access ( flash_message = nil ) respond_to do | format | format . any ( :js , :json , :xml ) { head :unauthorized } format . any { redirect_request ( flash_message ) } end end | Responds to unauthorized requests in a manner fitting the request format . js json and xml requests will receive a 401 with no body . All other formats will be redirected appropriately and can optionally have the flash message set . |
2,033 | def call ( env ) session = Clearance :: Session . new ( env ) env [ :clearance ] = session response = @app . call ( env ) session . add_cookie_to_headers response [ 1 ] response end | Reads previously existing sessions from a cookie and maintains the cookie on each response . |
2,034 | def send_file ( file , caption = nil , filename : nil , spoiler : nil ) pm . send_file ( file , caption : caption , filename : filename , spoiler : spoiler ) end | Send the user a file . |
2,035 | def update_presence ( data ) @status = data [ 'status' ] . to_sym if data [ 'game' ] game = data [ 'game' ] @game = game [ 'name' ] @stream_url = game [ 'url' ] @stream_type = game [ 'type' ] else @game = @stream_url = @stream_type = nil end end | Set the user s presence data |
2,036 | def permission? ( action , channel = nil ) return true if owner? return true if defined_permission? ( :administrator , channel ) defined_permission? ( action , channel ) end | Checks whether this user can do the particular action regardless of whether it has the permission defined through for example being the server owner or having the Manage Roles permission |
2,037 | def category = ( channel ) channel = @bot . channel ( channel ) raise ArgumentError , 'Cannot set parent category to a channel that isn\'t a category' unless channel . category? update_channel_data ( parent_id : channel . id ) end | Sets this channels parent category |
2,038 | def sort_after ( other = nil , lock_permissions = false ) raise TypeError , 'other must be one of Channel, NilClass, or #resolve_id' unless other . is_a? ( Channel ) || other . nil? || other . respond_to? ( :resolve_id ) other = @bot . channel ( other . resolve_id ) if other move_argument = [ ] if other raise ArgumentError , 'Can only sort a channel after a channel of the same type!' unless other . category? || ( @type == other . type ) raise ArgumentError , 'Can only sort a channel after a channel in the same server!' unless other . server == server parent = if category? && other . category? nil elsif other . category? other else other . parent end end ids = if parent parent . children else @server . channels . reject ( & :parent_id ) . select { | c | c . type == @type } end . sort_by ( & :position ) . map ( & :id ) ids . delete ( @id ) if ids . include? ( @id ) index = other ? ( ids . index { | c | c == other . id } || - 1 ) + 1 : 0 ids . insert ( index , @id ) ids . each_with_index do | id , pos | hash = { id : id , position : pos } if id == @id hash [ :lock_permissions ] = true if lock_permissions hash [ :parent_id ] = parent . nil? ? nil : parent . id end move_argument << hash end API :: Server . update_channel_positions ( @bot . token , @server . id , move_argument ) end | Sorts this channel s position to follow another channel . |
2,039 | def nsfw = ( nsfw ) raise ArgumentError , 'nsfw value must be true or false' unless nsfw . is_a? ( TrueClass ) || nsfw . is_a? ( FalseClass ) update_channel_data ( nsfw : nsfw ) end | Sets whether this channel is NSFW |
2,040 | def send_temporary_message ( content , timeout , tts = false , embed = nil ) @bot . send_temporary_message ( @id , content , timeout , tts , embed ) end | Sends a temporary message to this channel . |
2,041 | def send_embed ( message = '' , embed = nil ) embed ||= Discordrb :: Webhooks :: Embed . new yield ( embed ) if block_given? send_message ( message , false , embed ) end | Convenience method to send a message with an embed . |
2,042 | def send_file ( file , caption : nil , tts : false , filename : nil , spoiler : nil ) @bot . send_file ( @id , file , caption : caption , tts : tts , filename : filename , spoiler : spoiler ) end | Sends a file to this channel . If it is an image it will be embedded . |
2,043 | def delete_overwrite ( target , reason = nil ) raise 'Tried deleting a overwrite for an invalid target' unless target . is_a? ( Member ) || target . is_a? ( User ) || target . is_a? ( Role ) || target . is_a? ( Profile ) || target . is_a? ( Recipient ) || target . respond_to? ( :resolve_id ) API :: Channel . delete_permission ( @bot . token , @id , target . resolve_id , reason ) end | Deletes a permission overwrite for this channel |
2,044 | def update_from ( other ) @topic = other . topic @name = other . name @position = other . position @topic = other . topic @recipients = other . recipients @bitrate = other . bitrate @user_limit = other . user_limit @permission_overwrites = other . permission_overwrites @nsfw = other . nsfw @parent_id = other . parent_id @rate_limit_per_user = other . rate_limit_per_user end | Updates the cached data from another channel . |
2,045 | def users if text? @server . online_members ( include_idle : true ) . select { | u | u . can_read_messages? self } elsif voice? @server . voice_states . map { | id , voice_state | @server . member ( id ) if ! voice_state . voice_channel . nil? && voice_state . voice_channel . id == @id } . compact end end | The list of users currently in this channel . For a voice channel it will return all the members currently in that channel . For a text channel it will return all online members that have permission to read it . |
2,046 | def history ( amount , before_id = nil , after_id = nil , around_id = nil ) logs = API :: Channel . messages ( @bot . token , @id , amount , before_id , after_id , around_id ) JSON . parse ( logs ) . map { | message | Message . new ( message , @bot ) } end | Retrieves some of this channel s message history . |
2,047 | def history_ids ( amount , before_id = nil , after_id = nil , around_id = nil ) logs = API :: Channel . messages ( @bot . token , @id , amount , before_id , after_id , around_id ) JSON . parse ( logs ) . map { | message | message [ 'id' ] . to_i } end | Retrieves message history but only message IDs for use with prune . |
2,048 | def load_message ( message_id ) response = API :: Channel . message ( @bot . token , @id , message_id ) Message . new ( JSON . parse ( response ) , @bot ) rescue RestClient :: ResourceNotFound nil end | Returns a single message from this channel s history by ID . |
2,049 | def pins msgs = API :: Channel . pinned_messages ( @bot . token , @id ) JSON . parse ( msgs ) . map { | msg | Message . new ( msg , @bot ) } end | Requests all pinned messages in a channel . |
2,050 | def prune ( amount , strict = false , & block ) raise ArgumentError , 'Can only delete between 1 and 100 messages!' unless amount . between? ( 1 , 100 ) messages = if block_given? history ( amount ) . select ( & block ) . map ( & :id ) else history_ids ( amount ) end case messages . size when 0 0 when 1 API :: Channel . delete_message ( @bot . token , @id , messages . first ) 1 else bulk_delete ( messages , strict ) end end | Delete the last N messages on this channel . |
2,051 | def delete_messages ( messages , strict = false ) raise ArgumentError , 'Can only delete between 2 and 100 messages!' unless messages . count . between? ( 2 , 100 ) messages . map! ( & :resolve_id ) bulk_delete ( messages , strict ) end | Deletes a collection of messages |
2,052 | def make_invite ( max_age = 0 , max_uses = 0 , temporary = false , unique = false , reason = nil ) response = API :: Channel . create_invite ( @bot . token , @id , max_age , max_uses , temporary , unique , reason ) Invite . new ( JSON . parse ( response ) , @bot ) end | Creates a new invite to this channel . |
2,053 | def create_group ( user_ids ) raise 'Attempted to create group channel on a non-pm channel!' unless pm? response = API :: Channel . create_group ( @bot . token , @id , user_ids . shift ) channel = Channel . new ( JSON . parse ( response ) , @bot ) channel . add_group_users ( user_ids ) end | Creates a Group channel |
2,054 | def add_group_users ( user_ids ) raise 'Attempted to add a user to a non-group channel!' unless group? user_ids = [ user_ids ] unless user_ids . is_a? Array user_ids . each do | user_id | API :: Channel . add_group_user ( @bot . token , @id , user_id . resolve_id ) end self end | Adds a user to a group channel . |
2,055 | def remove_group_users ( user_ids ) raise 'Attempted to remove a user from a non-group channel!' unless group? user_ids = [ user_ids ] unless user_ids . is_a? Array user_ids . each do | user_id | API :: Channel . remove_group_user ( @bot . token , @id , user_id . resolve_id ) end self end | Removes a user from a group channel . |
2,056 | def webhooks raise 'Tried to request webhooks from a non-server channel' unless server webhooks = JSON . parse ( API :: Channel . webhooks ( @bot . token , @id ) ) webhooks . map { | webhook_data | Webhook . new ( webhook_data , @bot ) } end | Requests a list of Webhooks on the channel . |
2,057 | def invites raise 'Tried to request invites from a non-server channel' unless server invites = JSON . parse ( API :: Channel . invites ( @bot . token , @id ) ) invites . map { | invite_data | Invite . new ( invite_data , @bot ) } end | Requests a list of Invites to the channel . |
2,058 | def add_recipient ( recipient ) raise 'Tried to add recipient to a non-group channel' unless group? raise ArgumentError , 'Tried to add a non-recipient to a group' unless recipient . is_a? ( Recipient ) @recipients << recipient end | Adds a recipient to a group channel . |
2,059 | def remove_recipient ( recipient ) raise 'Tried to remove recipient from a non-group channel' unless group? raise ArgumentError , 'Tried to remove a non-recipient from a group' unless recipient . is_a? ( Recipient ) @recipients . delete ( recipient ) end | Removes a recipient from a group channel . |
2,060 | def bulk_delete ( ids , strict = false ) min_snowflake = IDObject . synthesise ( Time . now - TWO_WEEKS ) ids . reject! do | e | next unless e < min_snowflake message = "Attempted to bulk_delete message #{e} which is too old (min = #{min_snowflake})" raise ArgumentError , message if strict Discordrb :: LOGGER . warn ( message ) true end API :: Channel . bulk_delete_messages ( @bot . token , @id , ids ) ids . size end | Deletes a list of messages on this channel using bulk delete . |
2,061 | def include_events ( container ) handlers = container . instance_variable_get '@event_handlers' return unless handlers @event_handlers ||= { } @event_handlers . merge! ( handlers ) { | _ , old , new | old + new } end | Adds all event handlers from another container into this one . Existing event handlers will be overwritten . |
2,062 | def update ( data ) data [ :avatar ] = avatarise ( data [ :avatar ] ) if data . key? ( :avatar ) data [ :channel_id ] = data [ :channel ] . resolve_id data . delete ( :channel ) update_webhook ( data ) end | Updates the webhook if you need to edit more than 1 attribute . |
2,063 | def delete ( reason = nil ) if token? API :: Webhook . token_delete_webhook ( @token , @id , reason ) else API :: Webhook . delete_webhook ( @bot . token , @id , reason ) end end | Deletes the webhook . |
2,064 | def colour = ( value ) if value . nil? @colour = nil elsif value . is_a? Integer raise ArgumentError , 'Embed colour must be 24-bit!' if value >= 16_777_216 @colour = value elsif value . is_a? String self . colour = value . delete ( '#' ) . to_i ( 16 ) elsif value . is_a? Array raise ArgumentError , 'Colour tuple must have three values!' if value . length != 3 self . colour = value [ 0 ] << 16 | value [ 1 ] << 8 | value [ 2 ] else self . colour = value . to_i end end | Sets the colour of the bar to the side of the embed to something new . |
2,065 | def add_field ( name : nil , value : nil , inline : nil ) self << EmbedField . new ( name : name , value : value , inline : inline ) end | Convenience method to add a field to the embed without having to create one manually . |
2,066 | def profile response = Discordrb :: API :: User . profile ( @token ) LightProfile . new ( JSON . parse ( response ) , self ) end | Create a new LightBot . This does no networking yet all networking is done by the methods on this class . |
2,067 | def connections response = Discordrb :: API :: User . connections ( @token ) JSON . parse ( response ) . map { | e | Connection . new ( e , self ) } end | Gets the connections associated with this account . |
2,068 | def find_emoji ( name ) LOGGER . out ( "Resolving emoji #{name}" ) emoji . find { | element | element . name == name } end | Finds an emoji by its name . |
2,069 | def bot_application return unless @type == :bot response = API . oauth_application ( token ) Application . new ( JSON . parse ( response ) , self ) end | The bot s OAuth application . |
2,070 | def accept_invite ( invite ) resolved = invite ( invite ) . code API :: Invite . accept ( token , resolved ) end | Makes the bot join an invite to a server . |
2,071 | def send_message ( channel , content , tts = false , embed = nil ) channel = channel . resolve_id debug ( "Sending message to #{channel} with content '#{content}'" ) response = API :: Channel . create_message ( token , channel , content , tts , embed ? embed . to_hash : nil ) Message . new ( JSON . parse ( response ) , self ) end | Sends a text message to a channel given its ID and the message s content . |
2,072 | def send_temporary_message ( channel , content , timeout , tts = false , embed = nil ) Thread . new do Thread . current [ :discordrb_name ] = "#{@current_thread}-temp-msg" message = send_message ( channel , content , tts , embed ) sleep ( timeout ) message . delete end nil end | Sends a text message to a channel given its ID and the message s content then deletes it after the specified timeout in seconds . |
2,073 | def send_file ( channel , file , caption : nil , tts : false , filename : nil , spoiler : nil ) if file . respond_to? ( :read ) if spoiler filename ||= File . basename ( file . path ) filename = 'SPOILER_' + filename unless filename . start_with? 'SPOILER_' end file . define_singleton_method ( :original_filename ) { filename } if filename end channel = channel . resolve_id response = API :: Channel . upload_file ( token , channel , file , caption : caption , tts : tts ) Message . new ( JSON . parse ( response ) , self ) end | Sends a file to a channel . If it is an image it will automatically be embedded . |
2,074 | def create_server ( name , region = :' ' ) response = API :: Server . create ( token , name , region ) id = JSON . parse ( response ) [ 'id' ] . to_i sleep 0.1 until @servers [ id ] server = @servers [ id ] debug "Successfully created server #{server.id} with name #{server.name}" server end | Creates a server on Discord with a specified name and a region . |
2,075 | def update_oauth_application ( name , redirect_uris , description = '' , icon = nil ) API . update_oauth_application ( @token , name , redirect_uris , description , icon ) end | Changes information about your OAuth application |
2,076 | def parse_mentions ( mentions , server = nil ) array_to_return = [ ] while mentions . include? ( '<' ) && mentions . include? ( '>' ) mentions = mentions . split ( '<' , 2 ) [ 1 ] next unless mentions . split ( '>' , 2 ) . first . length < mentions . split ( '<' , 2 ) . first . length mention = mentions . split ( '>' , 2 ) . first if / \d / =~ mention array_to_return << user ( id ) unless user ( id ) . nil? elsif / \d / =~ mention array_to_return << channel ( id , server ) unless channel ( id , server ) . nil? elsif / \d / =~ mention if server array_to_return << server . role ( id ) unless server . role ( id ) . nil? else @servers . values . each do | element | array_to_return << element . role ( id ) unless element . role ( id ) . nil? end end elsif / \w \d / =~ mention array_to_return << ( emoji ( id ) || Emoji . new ( { 'animated' => ! animated . nil? , 'name' => name , 'id' => id } , self , nil ) ) end end array_to_return end | Gets the users channels roles and emoji from a string . |
2,077 | def update_status ( status , activity , url , since = 0 , afk = false , activity_type = 0 ) gateway_check @activity = activity @status = status @streamurl = url type = url ? 1 : activity_type activity_obj = activity || url ? { 'name' => activity , 'url' => url , 'type' => type } : nil @gateway . send_status_update ( status , since , activity_obj , afk ) profile . update_presence ( 'status' => status . to_s , 'game' => activity_obj ) end | Updates presence status . |
2,078 | def add_await! ( type , attributes = { } ) raise "You can't await an AwaitEvent!" if type == Discordrb :: Events :: AwaitEvent timeout = attributes [ :timeout ] raise ArgumentError , 'Timeout must be a number > 0' if timeout &. is_a? ( Numeric ) && ! timeout &. positive? mutex = Mutex . new cv = ConditionVariable . new response = nil block = lambda do | event | mutex . synchronize do response = event cv . signal end end handler = register_event ( type , attributes , block ) if timeout Thread . new do sleep timeout mutex . synchronize { cv . signal } end end mutex . synchronize { cv . wait ( mutex ) } remove_handler ( handler ) raise 'ConditionVariable was signaled without returning an event!' if response . nil? && timeout . nil? response end | Awaits an event blocking the current thread until a response is received . |
2,079 | def prune_empty_groups @channels . each_value do | channel | channel . leave_group if channel . group? && channel . recipients . empty? end end | Makes the bot leave any groups with no recipients remaining |
2,080 | def update_voice_state ( data ) @session_id = data [ 'session_id' ] server_id = data [ 'guild_id' ] . to_i server = server ( server_id ) return unless server user_id = data [ 'user_id' ] . to_i old_voice_state = server . voice_states [ user_id ] old_channel_id = old_voice_state . voice_channel . id if old_voice_state server . update_voice_state ( data ) old_channel_id end | Internal handler for VOICE_STATE_UPDATE |
2,081 | def update_voice_server ( data ) server_id = data [ 'guild_id' ] . to_i channel = @should_connect_to_voice [ server_id ] debug ( "Voice server update received! chan: #{channel.inspect}" ) return unless channel @should_connect_to_voice . delete ( server_id ) debug ( 'Updating voice server!' ) token = data [ 'token' ] endpoint = data [ 'endpoint' ] unless endpoint debug ( 'VOICE_SERVER_UPDATE sent with nil endpoint! Ignoring' ) return end debug ( 'Got data, now creating the bot.' ) @voices [ server_id ] = Discordrb :: Voice :: VoiceBot . new ( channel , self , token , @session_id , endpoint , @should_encrypt_voice ) end | Internal handler for VOICE_SERVER_UPDATE |
2,082 | def create_channel ( data ) channel = Channel . new ( data , self ) server = channel . server if server server . add_channel ( channel ) @channels [ channel . id ] = channel elsif channel . pm? @pm_channels [ channel . recipient . id ] = channel elsif channel . group? @channels [ channel . id ] = channel end end | Internal handler for CHANNEL_CREATE |
2,083 | def update_channel ( data ) channel = Channel . new ( data , self ) old_channel = @channels [ channel . id ] return unless old_channel old_channel . update_from ( channel ) end | Internal handler for CHANNEL_UPDATE |
2,084 | def delete_channel ( data ) channel = Channel . new ( data , self ) server = channel . server if server @channels . delete ( channel . id ) server . delete_channel ( channel . id ) elsif channel . pm? @pm_channels . delete ( channel . recipient . id ) elsif channel . group? @channels . delete ( channel . id ) end end | Internal handler for CHANNEL_DELETE |
2,085 | def add_recipient ( data ) channel_id = data [ 'channel_id' ] . to_i channel = self . channel ( channel_id ) recipient_user = ensure_user ( data [ 'user' ] ) recipient = Recipient . new ( recipient_user , channel , self ) channel . add_recipient ( recipient ) end | Internal handler for CHANNEL_RECIPIENT_ADD |
2,086 | def add_guild_member ( data ) server_id = data [ 'guild_id' ] . to_i server = self . server ( server_id ) member = Member . new ( data , server , self ) server . add_member ( member ) end | Internal handler for GUILD_MEMBER_ADD |
2,087 | def update_guild_member ( data ) server_id = data [ 'guild_id' ] . to_i server = self . server ( server_id ) member = server . member ( data [ 'user' ] [ 'id' ] . to_i ) member . update_roles ( data [ 'roles' ] ) member . update_nick ( data [ 'nick' ] ) end | Internal handler for GUILD_MEMBER_UPDATE |
2,088 | def delete_guild_member ( data ) server_id = data [ 'guild_id' ] . to_i server = self . server ( server_id ) user_id = data [ 'user' ] [ 'id' ] . to_i server . delete_member ( user_id ) rescue Discordrb :: Errors :: NoPermission Discordrb :: LOGGER . warn ( "delete_guild_member attempted to access a server for which the bot doesn't have permission! Not sure what happened here, ignoring" ) end | Internal handler for GUILD_MEMBER_DELETE |
2,089 | def update_guild_role ( data ) role_data = data [ 'role' ] server_id = data [ 'guild_id' ] . to_i server = @servers [ server_id ] new_role = Role . new ( role_data , self , server ) role_id = role_data [ 'id' ] . to_i old_role = server . roles . find { | r | r . id == role_id } old_role . update_from ( new_role ) end | Internal handler for GUILD_ROLE_UPDATE |
2,090 | def create_guild_role ( data ) role_data = data [ 'role' ] server_id = data [ 'guild_id' ] . to_i server = @servers [ server_id ] new_role = Role . new ( role_data , self , server ) existing_role = server . role ( new_role . id ) if existing_role existing_role . update_from ( new_role ) else server . add_role ( new_role ) end end | Internal handler for GUILD_ROLE_CREATE |
2,091 | def delete_guild_role ( data ) role_id = data [ 'role_id' ] . to_i server_id = data [ 'guild_id' ] . to_i server = @servers [ server_id ] server . delete_role ( role_id ) end | Internal handler for GUILD_ROLE_DELETE |
2,092 | def update_guild_emoji ( data ) server_id = data [ 'guild_id' ] . to_i server = @servers [ server_id ] server . update_emoji_data ( data ) end | Internal handler for GUILD_EMOJIS_UPDATE |
2,093 | def voice_regions return @voice_regions unless @voice_regions . empty? regions = JSON . parse API . voice_regions ( token ) regions . each do | data | @voice_regions [ data [ 'id' ] ] = VoiceRegion . new ( data ) end @voice_regions end | Returns or caches the available voice regions |
2,094 | def channel ( id , server = nil ) id = id . resolve_id raise Discordrb :: Errors :: NoPermission if @restricted_channels . include? id debug ( "Obtaining data for channel with id #{id}" ) return @channels [ id ] if @channels [ id ] begin begin response = API :: Channel . resolve ( token , id ) rescue RestClient :: ResourceNotFound return nil end channel = Channel . new ( JSON . parse ( response ) , self , server ) @channels [ id ] = channel rescue Discordrb :: Errors :: NoPermission debug "Tried to get access to restricted channel #{id}, blacklisting it" @restricted_channels << id raise end end | Gets a channel given its ID . This queries the internal channel cache and if the channel doesn t exist in there it will get the data from Discord . |
2,095 | def user ( id ) id = id . resolve_id return @users [ id ] if @users [ id ] LOGGER . out ( "Resolving user #{id}" ) begin response = API :: User . resolve ( token , id ) rescue RestClient :: ResourceNotFound return nil end user = User . new ( JSON . parse ( response ) , self ) @users [ id ] = user end | Gets a user by its ID . |
2,096 | def server ( id ) id = id . resolve_id return @servers [ id ] if @servers [ id ] LOGGER . out ( "Resolving server #{id}" ) begin response = API :: Server . resolve ( token , id ) rescue Discordrb :: Errors :: NoPermission return nil end server = Server . new ( JSON . parse ( response ) , self ) @servers [ id ] = server end | Gets a server by its ID . |
2,097 | def member ( server_or_id , user_id ) server_id = server_or_id . resolve_id user_id = user_id . resolve_id server = server_or_id . is_a? ( Server ) ? server_or_id : self . server ( server_id ) return server . member ( user_id ) if server . member_cached? ( user_id ) LOGGER . out ( "Resolving member #{server_id} on server #{user_id}" ) begin response = API :: Server . resolve_member ( token , server_id , user_id ) rescue RestClient :: ResourceNotFound return nil end member = Member . new ( JSON . parse ( response ) , server , self ) server . cache_member ( member ) end | Gets a member by both IDs or Server and user ID . |
2,098 | def ensure_user ( data ) if @users . include? ( data [ 'id' ] . to_i ) @users [ data [ 'id' ] . to_i ] else @users [ data [ 'id' ] . to_i ] = User . new ( data , self ) end end | Ensures a given user object is cached and if not cache it from the given data hash . |
2,099 | def ensure_server ( data ) if @servers . include? ( data [ 'id' ] . to_i ) @servers [ data [ 'id' ] . to_i ] else @servers [ data [ 'id' ] . to_i ] = Server . new ( data , self ) end end | Ensures a given server object is cached and if not cache it from the given data hash . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.