Class: Xasin::Telegram::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/xasin/telegram/Handler.rb

Overview

Main handler class, provides interfaces. It gives the user a way to send messages, set callbacks and retrieve chats with detailed data. More in-depth functions for messages are provided in the message class itself.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_core) ⇒ Handler

initialize a new Handler.

Parameters:

  • http_core (String, HTTPCore)

    The core to use, either a String representing the API Key, or an initialized Telegram Core



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/xasin/telegram/Handler.rb', line 83

def initialize(http_core)
	@core = if(http_core.is_a? Telegram::HTTPCore)
			http_core;
		elsif http_core.is_a? String
			Telegram::HTTPCore.new(http_core);
		else
			raise ArgumentError, "Could not make a valid HTTPCore from string!"
		end

	@core.attach_receptor(self);

	@chats = {}

	@on_telegram_event = []

	@permissions_list = {}
end

Instance Attribute Details

#coreObject (readonly)

Returns the Xasin::Telegram::HTTPCore used to communicate with Telegram.



35
36
37
# File 'lib/xasin/telegram/Handler.rb', line 35

def core
  @core
end

#permissions_listObject

Note:

The :sudo permission will always overwrite everything, use only for developer access!

List of permissions. Set this to a Hash containing arrays to included permissions, i.e. the following:

"admin" => ["default", "advanced"]

A user with “admin” would now also have “default” and “advanced” permissions for command execution.



49
50
51
# File 'lib/xasin/telegram/Handler.rb', line 49

def permissions_list
  @permissions_list
end

Class Method Details

.from_options(options) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/xasin/telegram/Handler.rb', line 51

def self.from_options(options)
	out_handler = Handler.new(options['Key']);

	if perms = options['Permissions']
		raise ArgumentError, 'Permission list must be a hash!' unless perms.is_a? Hash
		out_handler.permissions_list = perms
	end

	if u_list = options['Users']
		raise ArgumentError, 'Userlist must be a hash!' unless u_list.is_a? Hash

		u_list.each do |key, extra_opts|
			u = out_handler[key];

			unless u
				warn "User #{key} could not be found."
				next
			end

			if u_perms = extra_opts['Permissions']
				u.add_permissions u_perms
			end
		end
	end

	out_handler
end

Instance Method Details

#chat_from_id(num) ⇒ Object

Return the Chat with given ID. This will either return a known chat with the wanted ID, or else will call getChat to fetch details on the wanted chat and construct a new Chat object. May also return nil if the wanted chat does not exist!



188
189
190
191
192
193
194
195
196
197
198
# File 'lib/xasin/telegram/Handler.rb', line 188

def chat_from_id(num)
	if c = @chats[num]
		return c
	end

	chat_obj = @core.perform_post('getChat', { chat_id: num });

	return nil unless chat_obj[:ok]

	chat_from_object chat_obj[:result]
end

#chat_from_object(object) ⇒ Object

Return a Chat object directly constructed from the passed Hash.

Pass a Hash here to either fetch a chat with matching ID, or else constuct a new chat from the provided data. Can be used for getting a chat from a Message object, or adding a chat from stored chat configs.



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/xasin/telegram/Handler.rb', line 152

def chat_from_object(object)
	chat_id = object[:id];

	if c = @chats[chat_id]
		return c
	end

	c = nil;
	if object[:username]
		c = User.new(self, object);
	else
		c = Chat.new(self, object);
	end

	@chats[chat_id] = c;

	c
end

#chat_from_string(str) ⇒ Object

Try to find a chat with matching string ID. Useful when trying to find a chat by username, or a channel.



173
174
175
176
177
178
179
180
181
# File 'lib/xasin/telegram/Handler.rb', line 173

def chat_from_string(str)
	@chats.each do |_, chat|
		if chat.str_id == str
			return chat
		end
	end

	nil
end

#get_chat(object) ⇒ Object Also known as: []

Convenience function to get a chat by any means. Pass a Number (interpreted as Chat ID), String (username) or Hash into here to try and fetch a Chat based on the parameter. Chat ID is preferred as it will let the system fetch the Chat from Telegram’s API.



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/xasin/telegram/Handler.rb', line 205

def get_chat(object)
	if object.is_a? Chat
		object
	elsif object.is_a? Hash
		chat_from_object object;
	elsif object.is_a? Numeric
		chat_from_id object
	elsif object.is_a? String
		if object =~ /^@/
			chat_from_id object
		else
			chat_from_string object
		end
	end
end

#handle_packet(packet) ⇒ Object

Internal function, called from the Telegram Core. This is meant to be fed a Hash representing one update object from Telegram’s /getUpdate function



135
136
137
138
139
140
141
142
143
# File 'lib/xasin/telegram/Handler.rb', line 135

def handle_packet(packet)
	if m = packet[:message]
		handle_message m
	end

	if cbq = packet[:callback_query]
		handle_callback_query cbq
	end
end

#on_command(command, **options, &block) ⇒ Object

Add a new callback on any /command message. The provided block will be called whenever the fitting /command is called. Additionally, by setting a list of priorities (options = []), only certain users may be allowed to execute a command.

The block will be passed the message as argument.

Raises:

  • (ArgumentError)


284
285
286
287
288
289
290
291
292
293
294
# File 'lib/xasin/telegram/Handler.rb', line 284

def on_command(command, **options, &block)
	raise ArgumentError, 'Block must be given!' unless block_given?

	options[:block] = block
	options[:command] = command

	out_evt = OnCommand.new(options);
	@on_telegram_event << out_evt

	out_evt
end

#on_message(regexp = nil, &block) ⇒ Object

Add a new callback on any generic message. The provided block will be called with the Message as parameter when something arrives. May additionally specify a RegExp to match against, in which case the match is a second parameter to the block.

Raises:

  • (ArgumentError)


268
269
270
271
272
273
274
275
# File 'lib/xasin/telegram/Handler.rb', line 268

def on_message(regexp = nil, &block)
	raise ArgumentError, 'Block must be given!' unless block_given?

	out_evt = OnMessage.new({ block: block, regexp: regexp });
	@on_telegram_event << out_evt

	out_evt
end

#send_message(chat, text, **options) ⇒ Object

Note:

When a Inline Keyboard is used, the button presses are internally interpreted as messages. This way, they can feed into the /command syntax.

Send a message to a given chat. The following options are supported when sending:

  • silent: true/false, whether to enable or disable notification

  • reply_to: Message/nil, try to reply to the given message ID.

  • inline_keyboard: Hash or Array of Hashes, to set the inline keyboard

    with fitting commands.
    

Raises:

  • (ArgumentError)


233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/xasin/telegram/Handler.rb', line 233

def send_message(chat, text, **options)
	raise ArgumentError, "Text needs to be a string" unless text.is_a? String

	if text.length > 900
		text = text[0..900] + "..."
	end

	out_data = {
		chat_id: get_chat(chat).chat_id,
		parse_mode: 'HTML',
		text: text
	}

	if r = options[:reply_to]
		out_data[:reply_to_message_id] = r.to_i
	end

	if options[:silent]
		out_data[:disable_notification] = true;
	end

	if layout = options[:inline_keyboard]
		out_data[:reply_markup] = KeyboardLayout.new(layout).ilk_reply_markup
	end

	reply = @core.perform_post('sendMessage', out_data);

	Message.new(self, reply[:result]);
end