idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
2,100
def ensure_channel ( data , server = nil ) if @channels . include? ( data [ 'id' ] . to_i ) @channels [ data [ 'id' ] . to_i ] else @channels [ data [ 'id' ] . to_i ] = Channel . new ( data , self , server ) end end
Ensures a given channel object is cached and if not cache it from the given data hash .
2,101
def invite ( invite ) code = resolve_invite_code ( invite ) Invite . new ( JSON . parse ( API :: Invite . resolve ( token , code ) ) , self ) end
Gets information about an invite .
2,102
def find_channel ( channel_name , server_name = nil , type : nil ) results = [ ] if / \d / =~ channel_name return [ channel ( id ) ] end @servers . values . each do | server | server . channels . each do | channel | results << channel if channel . name == channel_name && ( server_name || server . name ) == server . name && ( ! type || ( channel . type == type ) ) end end results end
Finds a channel given its name and optionally the name of the server it is in .
2,103
def find_user ( username , discrim = nil ) users = @users . values . find_all { | e | e . username == username } return users . find { | u | u . discrim == discrim } if discrim users end
Finds a user given its username or username & discriminator .
2,104
def edit ( new_content , new_embed = nil ) response = API :: Channel . edit_message ( @bot . token , @channel . id , @id , new_content , [ ] , new_embed ? new_embed . to_hash : nil ) Message . new ( JSON . parse ( response ) , @bot ) end
Edits this message to have the specified content instead . You can only edit your own messages .
2,105
def create_reaction ( reaction ) reaction = reaction . to_reaction if reaction . respond_to? ( :to_reaction ) API :: Channel . create_reaction ( @bot . token , @channel . id , @id , reaction ) nil end
Reacts to a message .
2,106
def reacted_with ( reaction , limit : 100 ) reaction = reaction . to_reaction if reaction . respond_to? ( :to_reaction ) paginator = Paginator . new ( limit , :down ) do | last_page | after_id = last_page . last . id if last_page last_page = JSON . parse ( API :: Channel . get_reactions ( @bot . token , @channel . id , @id , reaction , nil , after_id , limit ) ) last_page . map { | d | User . new ( d , @bot ) } end paginator . to_a end
Returns the list of users who reacted with a certain reaction .
2,107
def delete_reaction ( user , reaction ) reaction = reaction . to_reaction if reaction . respond_to? ( :to_reaction ) API :: Channel . delete_user_reaction ( @bot . token , @channel . id , @id , reaction , user . resolve_id ) end
Deletes a reaction made by a user on this message .
2,108
def delete_own_reaction ( reaction ) reaction = reaction . to_reaction if reaction . respond_to? ( :to_reaction ) API :: Channel . delete_own_reaction ( @bot . token , @channel . id , @id , reaction ) end
Deletes this client s reaction on this message .
2,109
def process_users ( users ) users . each do | element | user = User . new ( element , @bot ) @users [ user . id ] = user end end
Process user objects given by the request
2,110
def process_webhooks ( webhooks ) webhooks . each do | element | webhook = Webhook . new ( element , @bot ) @webhooks [ webhook . id ] = webhook end end
Process webhook objects given by the request
2,111
def execute ( event ) old_chain = @chain @bot . debug 'Executing bare chain' result = execute_bare ( event ) @chain_args ||= [ ] @bot . debug "Found chain args #{@chain_args}, preliminary result #{result}" @chain_args . each do | arg | case arg . first when 'repeat' new_result = '' executed_chain = divide_chain ( old_chain ) . last arg [ 1 ] . to_i . times do chain_result = CommandChain . new ( executed_chain , @bot ) . execute ( event ) new_result += chain_result if chain_result end result = new_result end end result end
Divides the command chain into chain arguments and command chain then executes them both .
2,112
def update_from ( other ) @permissions = other . permissions @name = other . name @hoist = other . hoist @colour = other . colour @position = other . position @managed = other . managed end
Updates the data cache from another Role object
2,113
def update_data ( new_data ) @name = new_data [ :name ] || new_data [ 'name' ] || @name @hoist = new_data [ 'hoist' ] unless new_data [ 'hoist' ] . nil? @hoist = new_data [ :hoist ] unless new_data [ :hoist ] . nil? @colour = new_data [ :colour ] || ( new_data [ 'color' ] ? ColourRGB . new ( new_data [ 'color' ] ) : @colour ) end
Updates the data cache from a hash containing data
2,114
def packed = ( packed , update_perms = true ) update_role_data ( permissions : packed ) @permissions . bits = packed if update_perms end
Changes this role s permissions to a fixed bitfield . This allows setting multiple permissions at once with just one API call .
2,115
def sort_above ( other = nil ) other = @server . role ( other . resolve_id ) if other roles = @server . roles . sort_by ( & :position ) roles . delete_at ( @position ) index = other ? roles . index { | role | role . id == other . id } + 1 : 1 roles . insert ( index , self ) updated_roles = roles . map . with_index { | role , position | { id : role . id , position : position } } @server . update_role_positions ( updated_roles ) index end
Moves this role above another role in the list .
2,116
def set_roles ( role , reason = nil ) role_ids = role_id_array ( role ) API :: Server . update_member ( @bot . token , @server . id , @user . id , roles : role_ids , reason : reason ) end
Bulk sets a member s roles .
2,117
def modify_roles ( add , remove , reason = nil ) add_role_ids = role_id_array ( add ) remove_role_ids = role_id_array ( remove ) old_role_ids = @roles . map ( & :id ) new_role_ids = ( old_role_ids - remove_role_ids + add_role_ids ) . uniq API :: Server . update_member ( @bot . token , @server . id , @user . id , roles : new_role_ids , reason : reason ) end
Adds and removes roles from a member .
2,118
def add_role ( role , reason = nil ) role_ids = role_id_array ( role ) if role_ids . count == 1 API :: Server . add_member_role ( @bot . token , @server . id , @user . id , role_ids [ 0 ] , reason ) else old_role_ids = @roles . map ( & :id ) new_role_ids = ( old_role_ids + role_ids ) . uniq API :: Server . update_member ( @bot . token , @server . id , @user . id , roles : new_role_ids , reason : reason ) end end
Adds one or more roles to this member .
2,119
def remove_role ( role , reason = nil ) role_ids = role_id_array ( role ) if role_ids . count == 1 API :: Server . remove_member_role ( @bot . token , @server . id , @user . id , role_ids [ 0 ] , reason ) else old_role_ids = @roles . map ( & :id ) new_role_ids = old_role_ids . reject { | i | role_ids . include? ( i ) } API :: Server . update_member ( @bot . token , @server . id , @user . id , roles : new_role_ids , reason : reason ) end end
Removes one or more roles from this member .
2,120
def set_nick ( nick , reason = nil ) nick ||= '' if @user . current_bot? API :: User . change_own_nickname ( @bot . token , @server . id , nick , reason ) else API :: Server . update_member ( @bot . token , @server . id , @user . id , nick : nick , reason : nil ) end end
Sets or resets this member s nickname . Requires the Change Nickname permission for the bot itself and Manage Nicknames for other users .
2,121
def update_roles ( role_ids ) @roles = [ ] role_ids . each do | id | role = @server . role ( id ) @roles << role if role end end
Update this member s roles
2,122
def execute_command ( name , event , arguments , chained = false , check_permissions = true ) debug ( "Executing command #{name} with arguments #{arguments}" ) return unless @commands command = @commands [ name ] command = command . aliased_command if command . is_a? ( CommandAlias ) return unless ! check_permissions || channels? ( event . channel , @attributes [ :channels ] ) || ( command && ! command . attributes [ :channels ] . nil? ) unless command event . respond @attributes [ :command_doesnt_exist_message ] . gsub ( '%command%' , name . to_s ) if @attributes [ :command_doesnt_exist_message ] return end return unless ! check_permissions || channels? ( event . channel , command . attributes [ :channels ] ) arguments = arg_check ( arguments , command . attributes [ :arg_types ] , event . server ) if check_permissions if ( check_permissions && permission? ( event . author , command . attributes [ :permission_level ] , event . server ) && required_permissions? ( event . author , command . attributes [ :required_permissions ] , event . channel ) && required_roles? ( event . author , command . attributes [ :required_roles ] ) && allowed_roles? ( event . author , command . attributes [ :allowed_roles ] ) ) || ! check_permissions event . command = command result = command . call ( event , arguments , chained , check_permissions ) stringify ( result ) else event . respond command . attributes [ :permission_message ] . gsub ( '%name%' , name . to_s ) if command . attributes [ :permission_message ] nil end rescue Discordrb :: Errors :: NoPermission event . respond @attributes [ :no_permission_message ] unless @attributes [ :no_permission_message ] . nil? raise end
Executes a particular command on the bot . Mostly useful for internal stuff but one can never know .
2,123
def simple_execute ( chain , event ) return nil if chain . empty? args = chain . split ( ' ' ) execute_command ( args [ 0 ] . to_sym , event , args [ 1 .. - 1 ] ) end
Executes a command in a simple manner without command chains or permissions .
2,124
def permission? ( user , level , server ) determined_level = if user . webhook? || server . nil? 0 else user . roles . reduce ( 0 ) do | memo , role | [ @permissions [ :roles ] [ role . id ] || 0 , memo ] . max end end [ @permissions [ :users ] [ user . id ] || 0 , determined_level ] . max >= level end
Check if a user has permission to do something
2,125
def create_message ( data ) message = Discordrb :: Message . new ( data , self ) return message if message . from_bot? && ! @should_parse_self return message if message . webhook? && ! @attributes [ :webhook_commands ] unless message . author Discordrb :: LOGGER . warn ( "Received a message (#{message.inspect}) with nil author! Ignoring, please report this if you can" ) return end event = CommandEvent . new ( message , self ) chain = trigger? ( message ) return message unless chain if chain . start_with? ( ' ' ) && ! @attributes [ :spaces_allowed ] debug ( 'Chain starts with a space' ) return message end if chain . strip . empty? debug ( 'Chain is empty' ) return message end execute_chain ( chain , event ) message end
Internal handler for MESSAGE_CREATE that is overwritten to allow for command handling
2,126
def trigger? ( message ) if @prefix . is_a? String standard_prefix_trigger ( message . content , @prefix ) elsif @prefix . is_a? Array @prefix . map { | e | standard_prefix_trigger ( message . content , e ) } . reduce { | m , e | m || e } elsif @prefix . respond_to? :call @prefix . call ( message ) end end
Check whether a message should trigger command execution and if it does return the raw chain
2,127
def stop_playing ( wait_for_confirmation = false ) @was_playing_before = @playing @speaking = false @playing = false sleep IDEAL_LENGTH / 1000.0 if @was_playing_before return unless wait_for_confirmation @has_stopped_playing = false sleep IDEAL_LENGTH / 1000.0 until @has_stopped_playing @has_stopped_playing = false end
Stops the current playback entirely .
2,128
def play_dca ( file ) stop_playing ( true ) if @playing @bot . debug "Reading DCA file #{file}" input_stream = File . open ( file ) magic = input_stream . read ( 4 ) raise ArgumentError , 'Not a DCA1 file! The file might have been corrupted, please recreate it.' unless magic == 'DCA1' metadata_header = input_stream . read ( 4 ) . unpack1 ( 'l<' ) input_stream . read ( metadata_header ) play_internal do begin header_str = input_stream . read ( 2 ) unless header_str @bot . debug 'Finished DCA parsing (header is nil)' next :stop end header = header_str . unpack1 ( 's<' ) raise 'Negative header in DCA file! Your file is likely corrupted.' if header . negative? rescue EOFError @bot . debug 'Finished DCA parsing (EOFError)' next :stop end input_stream . read ( header ) end end
Plays a stream of audio data in the DCA format . This format has the advantage that no recoding has to be done - the file contains the data exactly as Discord needs it .
2,129
def play_internal count = 0 @playing = true @length = IDEAL_LENGTH self . speaking = true loop do should_adjust_this_packet = ( count % @adjust_interval == @adjust_offset ) @length_adjust = Time . now . nsec if should_adjust_this_packet break unless @playing if @skips . positive? @skips -= 1 yield next end count += 1 increment_packet_headers buf = yield break if buf == :stop next unless buf @intermediate_adjust = Time . now . nsec if should_adjust_this_packet @udp . send_audio ( buf , @sequence , @time ) @stream_time = count * @length / 1000 if @length_override @length = @length_override elsif @length_adjust now = Time . now . nsec ms_diff = ( now - @length_adjust ) / 1_000_000.0 if ms_diff >= 0 @length = if @adjust_average ( IDEAL_LENGTH - ms_diff + @length ) / 2.0 else IDEAL_LENGTH - ms_diff end encode_ms = ( @intermediate_adjust - @length_adjust ) / 1_000_000.0 @bot . debug ( "Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)" ) if @adjust_debug end @length_adjust = nil end sleep 0.1 while @paused if @length . positive? sleep @length / 1000.0 else Discordrb :: LOGGER . warn ( 'Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.' ) end end @bot . debug ( 'Sending five silent frames to clear out buffers' ) 5 . times do increment_packet_headers @udp . send_audio ( Encoder :: OPUS_SILENCE , @sequence , @time ) sleep IDEAL_LENGTH / 1000.0 end @bot . debug ( 'Performing final cleanup after stream ended' ) stop_playing @has_stopped_playing = true end
Plays the data from the
2,130
def execute ( builder = nil , wait = false ) raise TypeError , 'builder needs to be nil or like a Discordrb::Webhooks::Builder!' unless builder . respond_to? ( :file ) && builder . respond_to? ( :to_multipart_hash ) || builder . respond_to? ( :to_json_hash ) || builder . nil? builder ||= Builder . new yield builder if block_given? if builder . file post_multipart ( builder , wait ) else post_json ( builder , wait ) end end
Create a new webhook
2,131
def match ( event ) dummy_handler = EventContainer . handler_class ( @type ) . new ( @attributes , @bot ) return [ nil , nil ] unless event . instance_of? ( @type ) && dummy_handler . matches? ( event ) should_delete = nil should_delete = true if ( @block && @block . call ( event ) != false ) || ! @block [ @key , should_delete ] end
Makes a new await . For internal use only .
2,132
def drain_into ( result ) return if result . is_a? ( Discordrb :: Message ) result = ( @saved_message . nil? ? '' : @saved_message . to_s ) + ( result . nil? ? '' : result . to_s ) drain result end
Drains the currently saved message into a result string . This prepends it before that string clears the saved message and returns the concatenation .
2,133
def attach_file ( file , filename : nil , spoiler : nil ) raise ArgumentError , 'Argument is not a file!' unless file . is_a? ( File ) @file = file @filename = filename @file_spoiler = spoiler nil end
Attaches a file to the message event and converts the message into a caption .
2,134
def role ( id ) id = id . resolve_id @roles . find { | e | e . id == id } end
Gets a role on this server based on its ID .
2,135
def member ( id , request = true ) id = id . resolve_id return @members [ id ] if member_cached? ( id ) return nil unless request member = @bot . member ( self , id ) @members [ id ] = member unless member . nil? rescue StandardError nil end
Gets a member on this server based on user ID
2,136
def prune_count ( days ) raise ArgumentError , 'Days must be between 1 and 30' unless days . between? ( 1 , 30 ) response = JSON . parse API :: Server . prune_count ( @bot . token , @id , days ) response [ 'pruned' ] end
Returns the amount of members that are candidates for pruning
2,137
def delete_role ( role_id ) @roles . reject! { | r | r . id == role_id } @members . each do | _ , member | new_roles = member . roles . reject { | r | r . id == role_id } member . update_roles ( new_roles ) end @channels . each do | channel | overwrites = channel . permission_overwrites . reject { | id , _ | id == role_id } channel . update_overwrites ( overwrites ) end end
Removes a role from the role cache
2,138
def update_role_positions ( role_positions ) response = JSON . parse ( API :: Server . update_role_positions ( @bot . token , @id , role_positions ) ) response . each do | data | updated_role = Role . new ( data , @bot , self ) role ( updated_role . id ) . update_from ( updated_role ) end end
Updates the positions of all roles on the server
2,139
def update_voice_state ( data ) user_id = data [ 'user_id' ] . to_i if data [ 'channel_id' ] unless @voice_states [ user_id ] @voice_states [ user_id ] = VoiceState . new ( user_id ) end channel = @channels_by_id [ data [ 'channel_id' ] . to_i ] @voice_states [ user_id ] . update ( channel , data [ 'mute' ] , data [ 'deaf' ] , data [ 'self_mute' ] , data [ 'self_deaf' ] ) else @voice_states . delete ( user_id ) end end
Updates a member s voice state
2,140
def create_role ( name : 'new role' , colour : 0 , hoist : false , mentionable : false , permissions : 104_324_161 , reason : nil ) colour = colour . respond_to? ( :combined ) ? colour . combined : colour permissions = if permissions . is_a? ( Array ) Permissions . bits ( permissions ) elsif permissions . respond_to? ( :bits ) permissions . bits else permissions end response = API :: Server . create_role ( @bot . token , @id , name , colour , hoist , mentionable , permissions , reason ) role = Role . new ( JSON . parse ( response ) , @bot , self ) @roles << role role end
Creates a role on this server which can then be modified . It will be initialized with the regular role defaults the client uses unless specified i . e . name is new role permissions are the default colour is the default etc .
2,141
def add_emoji ( name , image , roles = [ ] , reason : nil ) image_string = image if image . respond_to? :read image_string = 'data:image/jpg;base64,' image_string += Base64 . strict_encode64 ( image . read ) end data = JSON . parse ( API :: Server . add_emoji ( @bot . token , @id , image_string , name , roles . map ( & :resolve_id ) , reason ) ) new_emoji = Emoji . new ( data ) @emoji [ new_emoji . id ] = new_emoji end
Adds a new custom emoji on this server .
2,142
def delete_emoji ( emoji , reason : nil ) API :: Server . delete_emoji ( @bot . token , @id , emoji . resolve_id , reason ) end
Delete a custom emoji on this server
2,143
def ban ( user , message_days = 0 , reason : nil ) API :: Server . ban_user ( @bot . token , @id , user . resolve_id , message_days , reason ) end
Bans a user from this server .
2,144
def unban ( user , reason = nil ) API :: Server . unban_user ( @bot . token , @id , user . resolve_id , reason ) end
Unbans a previously banned user from this server .
2,145
def kick ( user , reason = nil ) API :: Server . remove_member ( @bot . token , @id , user . resolve_id , reason ) end
Kicks a user from this server .
2,146
def move ( user , channel ) API :: Server . update_member ( @bot . token , @id , user . resolve_id , channel_id : channel . resolve_id ) end
Forcibly moves a user into a different voice channel . Only works if the bot has the permission needed .
2,147
def icon = ( icon ) if icon . respond_to? :read icon_string = 'data:image/jpg;base64,' icon_string += Base64 . strict_encode64 ( icon . read ) update_server_data ( icon_id : icon_string ) else update_server_data ( icon_id : icon ) end end
Sets the server s icon .
2,148
def verification_level = ( level ) level = VERIFICATION_LEVELS [ level ] if level . is_a? ( Symbol ) update_server_data ( verification_level : level ) end
Sets the verification level of the server
2,149
def default_message_notifications = ( notification_level ) notification_level = NOTIFICATION_LEVELS [ notification_level ] if notification_level . is_a? ( Symbol ) update_server_data ( default_message_notifications : notification_level ) end
Sets the default message notification level
2,150
def explicit_content_filter = ( filter_level ) filter_level = FILTER_LEVELS [ filter_level ] if filter_level . is_a? ( Symbol ) update_server_data ( explicit_content_filter : filter_level ) end
Sets the server content filter .
2,151
def webhooks webhooks = JSON . parse ( API :: Server . webhooks ( @bot . token , @id ) ) webhooks . map { | webhook | Webhook . new ( webhook , @bot ) } end
Requests a list of Webhooks on the server .
2,152
def invites invites = JSON . parse ( API :: Server . invites ( @bot . token , @id ) ) invites . map { | invite | Invite . new ( invite , @bot ) } end
Requests a list of Invites to the server .
2,153
def process_chunk ( members ) process_members ( members ) @processed_chunk_members += members . length LOGGER . debug ( "Processed one chunk on server #{@id} - length #{members.length}" ) return unless @processed_chunk_members == @member_count LOGGER . debug ( "Finished chunking server #{@id}" ) @chunked = true @processed_chunk_members = 0 end
Processes a GUILD_MEMBERS_CHUNK packet specifically the members field
2,154
def adjust_volume ( buf , mult ) return unless buf result = buf . unpack ( 's<*' ) . map do | sample | sample *= mult [ 32_767 , [ - 32_768 , sample ] . max ] . min end result . pack ( 's<*' ) end
Adjusts the volume of a given buffer of s16le PCM data .
2,155
def command ( name , attributes = { } , & block ) @commands ||= { } if name . is_a? Array new_command = nil name . each do | e | new_command = Command . new ( e , attributes , & block ) @commands [ e ] = new_command end new_command else new_command = Command . new ( name , attributes , & block ) new_command . attributes [ :aliases ] . each do | aliased_name | @commands [ aliased_name ] = CommandAlias . new ( aliased_name , new_command ) end @commands [ name ] = new_command end end
Adds a new command to the container .
2,156
def avatar = ( avatar ) if avatar . respond_to? :read avatar . binmode if avatar . respond_to? ( :binmode ) avatar_string = 'data:image/jpg;base64,' avatar_string += Base64 . strict_encode64 ( avatar . read ) update_profile_data ( avatar : avatar_string ) else update_profile_data ( avatar : avatar ) end end
Changes the bot s avatar .
2,157
def connect ( endpoint , port , ssrc ) @endpoint = endpoint @endpoint = @endpoint [ 6 .. - 1 ] if @endpoint . start_with? 'wss://' @endpoint = @endpoint . gsub ( ':80' , '' ) @endpoint = Resolv . getaddress @endpoint @port = port @ssrc = ssrc end
Creates a new UDP connection . Only creates a socket as the discovery reply may come before the data is initialized . Initializes the UDP socket with data obtained from opcode 2 .
2,158
def receive_discovery_reply message = @socket . recv ( 70 ) ip = message [ 4 .. - 3 ] . delete ( "\0" ) port = message [ - 2 .. - 1 ] . to_i [ ip , port ] end
Waits for a UDP discovery reply and returns the sent data .
2,159
def send_audio ( buf , sequence , time ) header = [ 0x80 , 0x78 , sequence , time , @ssrc ] . pack ( 'CCnNN' ) buf = encrypt_audio ( header , buf ) if encrypted? send_packet ( header + buf ) end
Makes an audio packet from a buffer and sends it to Discord .
2,160
def encrypt_audio ( header , buf ) raise 'No secret key found, despite encryption being enabled!' unless @secret_key box = RbNaCl :: SecretBox . new ( @secret_key ) nonce = header + ( [ 0 ] * 12 ) . pack ( 'C*' ) box . encrypt ( nonce , buf ) end
Encrypts audio data using RbNaCl
2,161
def rate_limited? ( key , thing , increment : 1 ) return false unless @buckets && @buckets [ key ] @buckets [ key ] . rate_limited? ( thing , increment : increment ) end
Performs a rate limit request .
2,162
def clean ( rate_limit_time = nil ) rate_limit_time ||= Time . now @bucket . delete_if do | _ , limit_hash | return false if @time_span && rate_limit_time < ( limit_hash [ :set_time ] + @time_span ) return false if @delay && rate_limit_time < ( limit_hash [ :last_time ] + @delay ) true end end
Makes a new bucket
2,163
def rate_limited? ( thing , rate_limit_time = nil , increment : 1 ) key = resolve_key thing limit_hash = @bucket [ key ] unless limit_hash @bucket [ key ] = { last_time : Time . now , set_time : Time . now , count : increment } return false end rate_limit_time ||= Time . now if @limit && ( limit_hash [ :count ] + increment ) > @limit return ( limit_hash [ :set_time ] + @time_span ) - rate_limit_time if @time_span && rate_limit_time < ( limit_hash [ :set_time ] + @time_span ) limit_hash [ :set_time ] = rate_limit_time limit_hash [ :count ] = 0 end if @delay && rate_limit_time < ( limit_hash [ :last_time ] + @delay ) ( limit_hash [ :last_time ] + @delay ) - rate_limit_time else limit_hash [ :last_time ] = rate_limit_time limit_hash [ :count ] += increment false end end
Performs a rate limiting request
2,164
def run_async @ws_thread = Thread . new do Thread . current [ :discordrb_name ] = 'websocket' connect_loop LOGGER . warn ( 'The WS loop exited! Not sure if this is a good thing' ) end LOGGER . debug ( 'WS thread created! Now waiting for confirmation that everything worked' ) sleep ( 0.5 ) until @ws_success LOGGER . debug ( 'Confirmation received! Exiting run.' ) end
Connect to the gateway server in a separate thread
2,165
def send_packet ( opcode , packet ) data = { op : opcode , d : packet } send ( data . to_json ) end
Sends a custom packet over the connection . This can be useful to implement future yet unimplemented functionality or for testing . You probably shouldn t use this unless you know what you re doing .
2,166
def obtain_socket ( uri ) socket = TCPSocket . new ( uri . host , uri . port || socket_port ( uri ) ) if secure_uri? ( uri ) ctx = OpenSSL :: SSL :: SSLContext . new if ENV [ 'DISCORDRB_SSL_VERIFY_NONE' ] ctx . ssl_version = 'SSLv23' ctx . verify_mode = OpenSSL :: SSL :: VERIFY_NONE cert_store = OpenSSL :: X509 :: Store . new cert_store . set_default_paths ctx . cert_store = cert_store else ctx . set_params ssl_version : :TLSv1_2 end socket = OpenSSL :: SSL :: SSLSocket . new ( socket , ctx ) socket . connect end socket end
Create and connect a socket using a URI
2,167
def target_schema ( link ) if link . target_schema link . target_schema elsif legacy_hyper_schema_rel? ( link ) link . parent end end
Gets the target schema of a link . This is normally just the standard response schema but we allow some legacy behavior for hyper - schema links tagged with rel = instances to instead use the schema of their parent resource .
2,168
def name ( gender = :any ) case gender when :any then rand ( 0 .. 1 ) == 0 ? name ( :male ) : name ( :female ) when :male then fetch_sample ( MALE_FIRST_NAMES ) when :female then fetch_sample ( FEMALE_FIRST_NAMES ) else raise ArgumentError , 'Invalid gender, must be one of :any, :male, :female' end end
A single name according to gender parameter
2,169
def mobile_prefix ( leading_zero = true ) mobile_prefix = '1' + rand ( 5 .. 7 ) . to_s + rand ( 0 .. 9 ) . to_s mobile_prefix = '0' + mobile_prefix if leading_zero mobile_prefix end
Mobile prefixes are in the 015x 016x 017x ranges
2,170
def validate! identify rescue MiniMagick :: Error => error raise MiniMagick :: Invalid , error . message end
Runs identify on the current image and raises an error if it doesn t pass .
2,171
def format ( format , page = 0 , read_opts = { } ) if @tempfile new_tempfile = MiniMagick :: Utilities . tempfile ( ".#{format}" ) new_path = new_tempfile . path else new_path = Pathname ( path ) . sub_ext ( ".#{format}" ) . to_s end input_path = path . dup input_path << "[#{page}]" if page && ! layer? MiniMagick :: Tool :: Convert . new do | convert | read_opts . each do | opt , val | convert . send ( opt . to_s , val ) end convert << input_path yield convert if block_given? convert << new_path end if @tempfile destroy! @tempfile = new_tempfile else File . delete ( path ) unless path == new_path || layer? end path . replace new_path @info . clear self end
This is used to change the format of the image . That is from tiff to jpg or something like that . Once you run it the instance is pointing to a new file with a new extension!
2,172
def identify MiniMagick :: Tool :: Identify . new do | builder | yield builder if block_given? builder << path end end
Runs identify on itself . Accepts an optional block for adding more options to identify .
2,173
def redact ( datum ) datum = datum . dup if datum . has_key? ( :headers ) && datum [ :headers ] . has_key? ( 'Authorization' ) datum [ :headers ] = datum [ :headers ] . dup datum [ :headers ] [ 'Authorization' ] = REDACTED end if datum . has_key? ( :password ) datum [ :password ] = REDACTED end datum end
Redact sensitive info from provided data
2,174
def split_header_value ( str ) return [ ] if str . nil? str = str . dup . strip binary_encode ( str ) str . scan ( %r' \G \\ \s \Z 'xn ) . flatten end
Splits a header value + str + according to HTTP specification .
2,175
def escape_uri ( str ) str = str . dup binary_encode ( str ) str . gsub ( UNESCAPED ) { "%%%02X" % $1 [ 0 ] . ord } end
Escapes HTTP reserved and unwise characters in + str +
2,176
def unescape_uri ( str ) str = str . dup binary_encode ( str ) str . gsub ( ESCAPED ) { $1 . hex . chr } end
Unescapes HTTP reserved and unwise characters in + str +
2,177
def unescape_form ( str ) str = str . dup binary_encode ( str ) str . gsub! ( / \+ / , ' ' ) str . gsub ( ESCAPED ) { $1 . hex . chr } end
Unescape form encoded values in + str +
2,178
def request ( params = { } , & block ) datum = @data . merge ( params ) datum [ :headers ] = @data [ :headers ] . merge ( datum [ :headers ] || { } ) validate_params ( :request , params , datum [ :middlewares ] ) if params [ :middlewares ] validate_params ( :connection , @data , datum [ :middlewares ] ) end if datum [ :user ] || datum [ :password ] user , pass = Utils . unescape_uri ( datum [ :user ] . to_s ) , Utils . unescape_uri ( datum [ :password ] . to_s ) datum [ :headers ] [ 'Authorization' ] ||= 'Basic ' + [ "#{user}:#{pass}" ] . pack ( 'm' ) . delete ( Excon :: CR_NL ) end if datum [ :scheme ] == UNIX datum [ :headers ] [ 'Host' ] ||= '' else datum [ :headers ] [ 'Host' ] ||= datum [ :host ] + port_string ( datum ) end unless datum [ :path ] [ 0 , 1 ] == '/' datum [ :path ] = datum [ :path ] . dup . insert ( 0 , '/' ) end if block_given? Excon . display_warning ( 'Excon requests with a block are deprecated, pass :response_block instead.' ) datum [ :response_block ] = Proc . new end datum [ :connection ] = self datum [ :stack ] = datum [ :middlewares ] . map do | middleware | lambda { | stack | middleware . new ( stack ) } end . reverse . inject ( self ) do | middlewares , middleware | middleware . call ( middlewares ) end datum = datum [ :stack ] . request_call ( datum ) unless datum [ :pipeline ] datum = response ( datum ) if datum [ :persistent ] if key = datum [ :response ] [ :headers ] . keys . detect { | k | k . casecmp ( 'Connection' ) == 0 } if datum [ :response ] [ :headers ] [ key ] . casecmp ( 'close' ) == 0 reset end end else reset end Excon :: Response . new ( datum [ :response ] ) else datum end rescue => error reset raise error if ! datum datum [ :error ] = error if datum [ :stack ] datum [ :stack ] . error_call ( datum ) else raise error end end
Sends the supplied request to the destination host .
2,179
def requests ( pipeline_params ) pipeline_params . each { | params | params . merge! ( :pipeline => true , :persistent => true ) } pipeline_params . last . merge! ( :persistent => @data [ :persistent ] ) responses = pipeline_params . map do | params | request ( params ) end . map do | datum | Excon :: Response . new ( response ( datum ) [ :response ] ) end if @data [ :persistent ] if key = responses . last [ :headers ] . keys . detect { | k | k . casecmp ( 'Connection' ) == 0 } if responses . last [ :headers ] [ key ] . casecmp ( 'close' ) == 0 reset end end else reset end responses end
Sends the supplied requests to the destination host using pipelining .
2,180
def batch_requests ( pipeline_params , limit = nil ) limit ||= Process . respond_to? ( :getrlimit ) ? Process . getrlimit ( :NOFILE ) . first : 256 responses = [ ] pipeline_params . each_slice ( limit ) do | params | responses . concat ( requests ( params ) ) end responses end
Sends the supplied requests to the destination host using pipelining in batches of
2,181
def start ARGV . clear IRB . setup nil IRB . conf [ :IRB_NAME ] = 'aruba' IRB . conf [ :PROMPT ] = { } IRB . conf [ :PROMPT ] [ :ARUBA ] = { PROMPT_I : '%N:%03n:%i> ' , PROMPT_S : '%N:%03n:%i%l ' , PROMPT_C : '%N:%03n:%i* ' , RETURN : "# => %s\n" } IRB . conf [ :PROMPT_MODE ] = :ARUBA IRB . conf [ :RC ] = false require 'irb/completion' require 'irb/ext/save-history' IRB . conf [ :READLINE ] = true IRB . conf [ :SAVE_HISTORY ] = 1000 IRB . conf [ :HISTORY_FILE ] = Aruba . config . console_history_file context = Class . new do include Aruba :: Api include Aruba :: Console :: Help def initialize setup_aruba end def inspect 'nil' end end irb = IRB :: Irb . new ( IRB :: WorkSpace . new ( context . new ) ) IRB . conf [ :MAIN_CONTEXT ] = irb . context trap ( "SIGINT" ) do irb . signal_handle end begin catch ( :IRB_EXIT ) do irb . eval_input end ensure IRB . irb_at_exit end end
Start the aruba console
2,182
def make_copy obj = self . dup obj . local_options = Marshal . load ( Marshal . dump ( local_options ) ) obj . hooks = @hooks obj end
Make deep dup copy of configuration
2,183
def before ( name , context = proc { } , * args , & block ) name = format ( '%s_%s' , 'before_' , name . to_s ) . to_sym if block_given? @hooks . append ( name , block ) self else @hooks . execute ( name , context , * args ) end end
Define or run before - hook
2,184
def notify ( event ) fail NoEventError , 'Please pass an event object, not a class' if event . is_a? ( Class ) @handlers [ event . class . to_s ] . each { | handler | handler . call ( event ) } end
Broadcast an event
2,185
def fixtures_directory @fixtures_directory ||= begin candidates = config . fixtures_directories . map { | dir | File . join ( root_directory , dir ) } directory = candidates . find { | d | Aruba . platform . directory? d } fail "No existing fixtures directory found in #{candidates.map { |d| format('"%s"', d) }.join(', ')}." unless directory directory end fail %(Fixtures directory "#{@fixtures_directory}" is not a directory) unless Aruba . platform . directory? ( @fixtures_directory ) ArubaPath . new ( @fixtures_directory ) end
The path to the directory which contains fixtures You might want to overwrite this method to place your data else where .
2,186
def call ( test_framework ) begin initializers . find { | i | i . match? test_framework } . start [ ] , { } rescue ArgumentError => e $stderr . puts e . message exit 0 end Initializers :: CommonInitializer . start [ ] , { } end
Create files etc .
2,187
def append ( label , block ) if store . key? ( label . to_sym ) && store [ label . to_sym ] . respond_to? ( :<< ) store [ label . to_sym ] << block else store [ label . to_sym ] = [ ] store [ label . to_sym ] << block end end
Create store Add new hook
2,188
def find ( path ) results = [ ] Find . find ( path ) do | fpath | if FileTest . directory? ( fpath ) next unless ignores ignores . each do | ignore | next unless fpath . include? ( ignore . realpath . to_s ) puts "Ignoring Directory: #{fpath}" if options [ :verbose ] Find . prune end end results << fpath if yield fpath end results end
Find all files for which the block yields .
2,189
def keys ( pattern = SCAN_PATTERN , count = DEFAULT_COUNT ) return redis ( & :keys ) if pattern . nil? redis { | conn | conn . scan_each ( match : prefix ( pattern ) , count : count ) . to_a } end
Find unique keys in redis
2,190
def keys_with_ttl ( pattern = SCAN_PATTERN , count = DEFAULT_COUNT ) hash = { } redis do | conn | conn . scan_each ( match : prefix ( pattern ) , count : count ) . each do | key | hash [ key ] = conn . ttl ( key ) end end hash end
Find unique keys with ttl
2,191
def del ( pattern = SCAN_PATTERN , count = 0 ) raise ArgumentError , "Please provide a number of keys to delete greater than zero" if count . zero? pattern = suffix ( pattern ) log_debug { "Deleting keys by: #{pattern}" } keys , time = timed { keys ( pattern , count ) } key_size = keys . size log_debug { "#{key_size} keys found in #{time} sec." } _ , time = timed { batch_delete ( keys ) } log_debug { "Deleted #{key_size} keys in #{time} sec." } key_size end
Deletes unique keys from redis
2,192
def unlock ( item ) SidekiqUniqueJobs :: UniqueArgs . digest ( item ) SidekiqUniqueJobs :: Locksmith . new ( item ) . unlock end
Unlocks a job .
2,193
def delete ( item ) SidekiqUniqueJobs :: UniqueArgs . digest ( item ) SidekiqUniqueJobs :: Locksmith . new ( item ) . delete! end
Deletes a lock regardless of if it was locked or not .
2,194
def call ( file_name , redis_pool , options = { } ) execute_script ( file_name , redis_pool , options ) rescue Redis :: CommandError => ex handle_error ( ex , file_name ) do call ( file_name , redis_pool , options ) end end
Call a lua script with the provided file_name
2,195
def execute_script ( file_name , redis_pool , options = { } ) redis ( redis_pool ) do | conn | sha = script_sha ( conn , file_name ) conn . evalsha ( sha , options ) end end
Execute the script file
2,196
def script_sha ( conn , file_name ) if ( sha = SCRIPT_SHAS . get ( file_name ) ) return sha end sha = conn . script ( :load , script_source ( file_name ) ) SCRIPT_SHAS . put ( file_name , sha ) sha end
Return sha of already loaded lua script or load it and return the sha
2,197
def handle_error ( ex , file_name ) if ex . message == "NOSCRIPT No matching script. Please use EVAL." SCRIPT_SHAS . delete ( file_name ) return yield if block_given? end raise ScriptError , file_name : file_name , source_exception : ex end
Handle errors to allow retrying errors that need retrying
2,198
def delete! Scripts . call ( :delete , redis_pool , keys : [ exists_key , grabbed_key , available_key , version_key , UNIQUE_SET , unique_digest ] , ) end
Deletes the lock regardless of if it has a ttl set
2,199
def lock ( timeout = nil , & block ) Scripts . call ( :lock , redis_pool , keys : [ exists_key , grabbed_key , available_key , UNIQUE_SET , unique_digest ] , argv : [ jid , ttl , lock_type ] ) grab_token ( timeout ) do | token | touch_grabbed_token ( token ) return_token_or_block_value ( token , & block ) end end
Create a lock for the item