forked from zammad/zammad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.rb
718 lines (603 loc) · 20.2 KB
/
telegram.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# Copyright (C) 2012-2015 Zammad Foundation, http://zammad-foundation.org/
class Telegram
attr_accessor :client
=begin
check token and return bot attributes of token
bot = Telegram.check_token('token')
=end
def self.check_token(token)
api = TelegramAPI.new(token)
begin
bot = api.getMe()
rescue
raise 'invalid api token'
end
bot
end
=begin
set webhool for bot
success = Telegram.set_webhook('token', callback_url)
returns
true|false
=end
def self.set_webhook(token, callback_url)
if callback_url.match?(%r{^http://}i)
raise 'webhook url need to start with https://, you use http://'
end
api = TelegramAPI.new(token)
begin
api.setWebhook(callback_url)
rescue
raise 'Unable to set webhook at Telegram, seems to be a invalid url.'
end
true
end
=begin
create or update channel, store bot attributes and verify token
channel = Telegram.create_or_update_channel('token', params)
returns
channel # instance of Channel
=end
def self.create_or_update_channel(token, params, channel = nil)
# verify token
bot = Telegram.check_token(token)
if !channel
if Telegram.bot_duplicate?(bot['id'])
raise 'Bot already exists!'
end
end
if params[:group_id].blank?
raise 'Group needed!'
end
group = Group.find_by(id: params[:group_id])
if !group
raise 'Group invalid!'
end
# generate randam callback token
callback_token = if Rails.env.test?
'callback_token'
else
SecureRandom.urlsafe_base64(10)
end
# set webhook / callback url for this bot @ telegram
callback_url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/channels_telegram_webhook/#{callback_token}?bid=#{bot['id']}"
Telegram.set_webhook(token, callback_url)
if !channel
channel = Telegram.bot_by_bot_id(bot['id'])
if !channel
channel = Channel.new
end
end
channel.area = 'Telegram::Bot'
channel.options = {
bot: {
id: bot['id'],
username: bot['username'],
first_name: bot['first_name'],
last_name: bot['last_name'],
},
callback_token: callback_token,
callback_url: callback_url,
api_token: token,
welcome: params[:welcome],
}
channel.group_id = group.id
channel.active = true
channel.save!
channel
end
=begin
check if bot already exists as channel
success = Telegram.bot_duplicate?(bot_id)
returns
channel # instance of Channel
=end
def self.bot_duplicate?(bot_id, channel_id = nil)
Channel.where(area: 'Telegram::Bot').each do |channel|
next if !channel.options
next if !channel.options[:bot]
next if !channel.options[:bot][:id]
next if channel.options[:bot][:id] != bot_id
next if channel.id.to_s == channel_id.to_s
return true
end
false
end
=begin
get channel by bot_id
channel = Telegram.bot_by_bot_id(bot_id)
returns
true|false
=end
def self.bot_by_bot_id(bot_id)
Channel.where(area: 'Telegram::Bot').each do |channel|
next if !channel.options
next if !channel.options[:bot]
next if !channel.options[:bot][:id]
return channel if channel.options[:bot][:id].to_s == bot_id.to_s
end
nil
end
=begin
generate message_id for message
message_id = Telegram.message_id(message)
returns
message_id # 123456@telegram
=end
def self.message_id(params)
message_id = nil
%i[message edited_message].each do |key|
next if !params[key]
next if !params[key][:message_id]
message_id = params[key][:message_id]
break
end
if message_id
%i[message edited_message].each do |key|
next if !params[key]
next if !params[key][:chat]
next if !params[key][:chat][:id]
message_id = "#{message_id}.#{params[key][:chat][:id]}"
end
end
if !message_id
message_id = params[:update_id]
end
"#{message_id}@telegram"
end
=begin
client = Telegram.new('token')
=end
def initialize(token)
@token = token
@api = TelegramAPI.new(token)
end
=begin
client.message(chat_id, 'some message')
=end
def message(chat_id, message)
return if Rails.env.test?
@api.sendMessage(chat_id, message)
end
def user(params)
{
id: params[:message][:from][:id],
username: params[:message][:from][:username],
first_name: params[:message][:from][:first_name],
last_name: params[:message][:from][:last_name]
}
end
def to_user(params)
Rails.logger.debug { 'Create user from message...' }
Rails.logger.debug { params.inspect }
# do message_user lookup
message_user = user(params)
auth = Authorization.find_by(uid: message_user[:id], provider: 'telegram')
# create or update user
login = message_user[:username] || message_user[:id]
user_data = {
login: login,
firstname: message_user[:first_name],
lastname: message_user[:last_name],
}
if auth
user = User.find(auth.user_id)
user.update!(user_data)
else
if message_user[:username]
user_data[:note] = "Telegram @#{message_user[:username]}"
end
user_data[:active] = true
user_data[:role_ids] = Role.signup_role_ids
user = User.create(user_data)
end
# create or update authorization
auth_data = {
uid: message_user[:id],
username: login,
user_id: user.id,
provider: 'telegram'
}
if auth
auth.update!(auth_data)
else
Authorization.create(auth_data)
end
user
end
def to_ticket(params, user, group_id, channel)
UserInfo.current_user_id = user.id
Rails.logger.debug { 'Create ticket from message...' }
Rails.logger.debug { params.inspect }
Rails.logger.debug { user.inspect }
Rails.logger.debug { group_id.inspect }
# prepare title
title = '-'
%i[text caption].each do |area|
next if !params[:message]
next if !params[:message][area]
title = params[:message][area]
break
end
if title == '-'
%i[sticker photo document voice].each do |area|
begin
next if !params[:message]
next if !params[:message][area]
next if !params[:message][area][:emoji]
title = params[:message][area][:emoji]
break
rescue
# just go ahead
title
end
end
end
if title.length > 60
title = "#{title[0, 60]}..."
end
# find ticket or create one
state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
ticket = Ticket.where(customer_id: user.id).where.not(state_id: state_ids).order(:updated_at).first
if ticket
# check if title need to be updated
if ticket.title == '-'
ticket.title = title
end
new_state = Ticket::State.find_by(default_create: true)
if ticket.state_id != new_state.id
ticket.state = Ticket::State.find_by(default_follow_up: true)
end
ticket.save!
return ticket
end
ticket = Ticket.new(
group_id: group_id,
title: title,
state_id: Ticket::State.find_by(default_create: true).id,
priority_id: Ticket::Priority.find_by(default_create: true).id,
customer_id: user.id,
preferences: {
channel_id: channel.id,
telegram: {
bid: params['bid'],
chat_id: params[:message][:chat][:id]
}
},
)
ticket.save!
ticket
end
def to_article(params, user, ticket, channel, article = nil)
if article
Rails.logger.debug { 'Update article from message...' }
else
Rails.logger.debug { 'Create article from message...' }
end
Rails.logger.debug { params.inspect }
Rails.logger.debug { user.inspect }
Rails.logger.debug { ticket.inspect }
UserInfo.current_user_id = user.id
if article
article.preferences[:edited_message] = {
message: {
created_at: params[:message][:date],
message_id: params[:message][:message_id],
from: params[:message][:from],
},
update_id: params[:update_id],
}
else
article = Ticket::Article.new(
ticket_id: ticket.id,
type_id: Ticket::Article::Type.find_by(name: 'telegram personal-message').id,
sender_id: Ticket::Article::Sender.find_by(name: 'Customer').id,
from: user(params)[:username],
to: "@#{channel[:options][:bot][:username]}",
message_id: Telegram.message_id(params),
internal: false,
preferences: {
message: {
created_at: params[:message][:date],
message_id: params[:message][:message_id],
from: params[:message][:from],
},
update_id: params[:update_id],
}
)
end
# add article
if params[:message][:photo]
# find photo with best resolution for us
photo = nil
max_width = 650 * 2
last_width = 0
last_height = 0
params[:message][:photo].each do |file|
if !photo
photo = file
last_width = file['width'].to_i
last_height = file['height'].to_i
end
next if file['width'].to_i >= max_width || file['width'].to_i <= last_width
photo = file
last_width = file['width'].to_i
last_height = file['height'].to_i
end
if last_width > 650
last_width = (last_width / 2).to_i
last_height = (last_height / 2).to_i
end
# download image
result = download_file(photo['file_id'])
if !result.success? || !result.body
raise "Unable for download image from telegram: #{result.code}"
end
body = "<img style=\"width:#{last_width}px;height:#{last_height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
if params[:message][:caption]
body += "<br>#{params[:message][:caption].text2html}"
end
article.content_type = 'text/html'
article.body = body
article.save!
return article
end
# add document
if params[:message][:document]
thumb = params[:message][:document][:thumb]
body = ' '
if thumb
width = thumb[:width]
height = thumb[:height]
result = download_file(thumb['file_id'])
if !result.success? || !result.body
raise "Unable for download image from telegram: #{result.code}"
end
body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/png;base64,#{Base64.strict_encode64(result.body)}\">"
end
document_result = download_file(params[:message][:document][:file_id])
article.content_type = 'text/html'
article.body = body
article.save!
Store.remove(
object: 'Ticket::Article',
o_id: article.id,
)
Store.add(
object: 'Ticket::Article',
o_id: article.id,
data: document_result.body,
filename: params[:message][:document][:file_name],
preferences: {
'Mime-Type' => params[:message][:document][:mime_type],
},
)
return article
end
# voice
if params[:message][:voice]
body = ' '
if params[:message][:caption]
body = "<br>#{params[:message][:caption].text2html}"
end
document_result = download_file(params[:message][:voice][:file_id])
article.content_type = 'text/html'
article.body = body
article.save!
Store.remove(
object: 'Ticket::Article',
o_id: article.id,
)
Store.add(
object: 'Ticket::Article',
o_id: article.id,
data: document_result.body,
filename: params[:message][:voice][:file_path] || "audio-#{params[:message][:voice][:file_id]}.ogg",
preferences: {
'Mime-Type' => params[:message][:voice][:mime_type],
},
)
return article
end
if params[:message][:sticker]
emoji = params[:message][:sticker][:emoji]
thumb = params[:message][:sticker][:thumb]
body = ' '
if thumb
width = thumb[:width]
height = thumb[:height]
result = download_file(thumb['file_id'])
if !result.success? || !result.body
raise "Unable for download image from telegram: #{result.code}"
end
body = "<img style=\"width:#{width}px;height:#{height}px;\" src=\"data:image/webp;base64,#{Base64.strict_encode64(result.body)}\">"
article.content_type = 'text/html'
elsif emoji
article.content_type = 'text/plain'
body = emoji
end
article.body = body
article.save!
if params[:message][:sticker][:file_id]
document_result = download_file(params[:message][:sticker][:file_id])
Store.remove(
object: 'Ticket::Article',
o_id: article.id,
)
Store.add(
object: 'Ticket::Article',
o_id: article.id,
data: document_result.body,
filename: params[:message][:sticker][:file_name] || "#{params[:message][:sticker][:set_name]}.webp",
preferences: {
'Mime-Type' => 'image/webp', # mime type is not given from Telegram API but this is actually WebP
},
)
end
return article
end
# text
if params[:message][:text]
article.content_type = 'text/plain'
article.body = params[:message][:text]
article.save!
return article
end
raise 'invalid action'
end
def to_group(params, group_id, channel)
# begin import
Rails.logger.debug { 'import message' }
# map channel_post params to message
if params[:channel_post]
return if params[:channel_post][:new_chat_title] # happens when channel title is renamed, we use [:chat][:title] already, safely ignore this.
# note: used .blank? which is a rails method. empty? does not work on integers (values like date, width, height) to check.
# need delete_if to remove any empty hashes, .compact only removes keys with nil values.
params[:message] = {
document: {
file_name: params.dig(:channel_post, :document, :file_name),
mime_type: params.dig(:channel_post, :document, :mime_type),
file_id: params.dig(:channel_post, :document, :file_id),
file_size: params.dig(:channel_post, :document, :filesize),
thumb: {
file_id: params.dig(:channel_post, :document, :thumb, :file_id),
file_size: params.dig(:channel_post, :document, :thumb, :file_size),
width: params.dig(:channel_post, :document, :thumb, :width),
height: params.dig(:channel_post, :document, :thumb, :height)
}.compact
}.delete_if { |_, v| v.blank? },
voice: {
duration: params.dig(:channel_post, :voice, :duration),
mime_type: params.dig(:channel_post, :voice, :mime_type),
file_id: params.dig(:channel_post, :voice, :file_id),
file_size: params.dig(:channel_post, :voice, :file_size)
}.compact,
sticker: {
width: params.dig(:channel_post, :sticker, :width),
height: params.dig(:channel_post, :sticker, :height),
emoji: params.dig(:channel_post, :sticker, :emoji),
set_name: params.dig(:channel_post, :sticker, :set_name),
file_id: params.dig(:channel_post, :sticker, :file_id),
file_path: params.dig(:channel_post, :sticker, :file_path),
thumb: {
file_id: params.dig(:channel_post, :sticker, :thumb, :file_id),
file_size: params.dig(:channel_post, :sticker, :thumb, :file_size),
width: params.dig(:channel_post, :sticker, :thumb, :width),
height: params.dig(:channel_post, :sticker, :thumb, :file_id),
file_path: params.dig(:channel_post, :sticker, :thumb, :file_path)
}.compact
}.delete_if { |_, v| v.blank? },
chat: {
id: params.dig(:channel_post, :chat, :id),
first_name: params.dig(:channel_post, :chat, :title),
last_name: 'Channel',
username: "channel#{params.dig(:channel_post, :chat, :id)}"
},
from: {
id: params.dig(:channel_post, :chat, :id),
first_name: params.dig(:channel_post, :chat, :title),
last_name: 'Channel',
username: "channel#{params.dig(:channel_post, :chat, :id)}"
},
caption: (params.dig(:channel_post, :caption) || {}),
date: params.dig(:channel_post, :date),
message_id: params.dig(:channel_post, :message_id),
text: params.dig(:channel_post, :text),
photo: (params[:channel_post][:photo].map { |photo| { file_id: photo[:file_id], file_size: photo[:file_size], width: photo[:width], height: photo[:height] } } if params.dig(:channel_post, :photo))
}.delete_if { |_, v| v.blank? }
params.delete(:channel_post) # discard unused :channel_post hash
end
# checks if the channel post is being edited, and map it when it is
if params[:edited_channel_post]
# updates on telegram can only be on messages, no attachments
params[:edited_message] = {
chat: {
id: params.dig(:edited_channel_post, :chat, :id),
first_name: params.dig(:edited_channel_post, :chat, :title),
last_name: 'Channel',
username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
},
from: {
id: params.dig(:edited_channel_post, :chat, :id),
first_name: params.dig(:edited_channel_post, :chat, :title),
last_name: 'Channel',
username: "channel#{params.dig(:edited_channel_post, :chat, :id)}"
},
date: params.dig(:edited_channel_post, :date),
edit_date: params.dig(:edited_channel_post, :edit_date),
message_id: params.dig(:edited_channel_post, :message_id),
text: params.dig(:edited_channel_post, :text)
}
params.delete(:edited_channel_post) # discard unused :edited_channel_post hash
end
# prevent multible update
if !params[:edited_message]
return if Ticket::Article.find_by(message_id: Telegram.message_id(params))
end
# update article
if params[:edited_message]
article = Ticket::Article.find_by(message_id: Telegram.message_id(params))
return if !article
params[:message] = params[:edited_message]
user = to_user(params)
to_article(params, user, article.ticket, channel, article)
return article
end
# send welcome message and don't create ticket
text = params[:message][:text]
if text.present? && text =~ %r{^/start}
message(params[:message][:chat][:id], channel.options[:welcome] || 'You are welcome! Just ask me something!')
return
# find ticket and close it
elsif text.present? && text =~ %r{^/end}
user = to_user(params)
ticket = Ticket.where(customer_id: user.id).order(:updated_at).first
ticket.state = Ticket::State.find_by(name: 'closed')
ticket.save!
return
end
ticket = nil
# use transaction
Transaction.execute(reset_user_id: true) do
user = to_user(params)
ticket = to_ticket(params, user, group_id, channel)
to_article(params, user, ticket, channel)
end
ticket
end
def from_article(article)
message = nil
Rails.logger.debug { "Create telegram personal message from article to '#{article[:to]}'..." }
message = {}
# TODO: create telegram message here
Rails.logger.debug { message.inspect }
message
end
def get_state(channel, telegram_update, ticket = nil)
message = telegram_update['message']
message_user = user(message)
# no changes in post is from page user it self
if channel.options[:bot][:id].to_s == message_user[:id].to_s
if !ticket
return Ticket::State.find_by(name: 'closed') if !ticket
end
return ticket.state
end
state = Ticket::State.find_by(default_create: true)
return state if !ticket
return ticket.state if ticket.state.id == state.id
Ticket::State.find_by(default_follow_up: true)
end
def download_file(file_id)
document = @api.getFile(file_id)
url = "https://api.telegram.org/file/bot#{@token}/#{document['file_path']}"
UserAgent.get(
url,
{},
{
open_timeout: 20,
read_timeout: 40,
},
)
end
end