-
Notifications
You must be signed in to change notification settings - Fork 1
/
Telegram Connector.xml
795 lines (658 loc) · 25.2 KB
/
Telegram Connector.xml
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE MudletPackage>
<MudletPackage version="1.001">
<TriggerPackage />
<TimerPackage />
<AliasPackage />
<ActionPackage />
<ScriptPackage>
<Script isActive="yes" isFolder="no">
<name>TelegramMainScript</name>
<packageName></packageName>
<script>-- #########################################################################
-- TODO
-- * Add #COMMANDS
-- * #TELEGRAM CONFIGURE
-- * #TELEGRAM ENABLE/DISABLE
-- * #TELEGRAM VERSION
-- * #TELEGRAM HELP
-- * #TELEGRAM UPDATE
-- * #HELP
-- * #VERSION
-- * #ABOUT
-- #########################################################################
-- Telegram configure
-- -> collect and store Token and update interval
-- -> also allow setting a char name, or use Profile Name
-- -> also allowed "senders"
--
Telegram = Telegram or {}
Telegram.Version = "0.0.0"
local url_versionDownload = "https://github.com/takilara/MudletTelegramConnector/releases/latest/download/version.lua"
local url_latestVersion = "https://github.com/takilara/MudletTelegramConnector/releases/latest/download/"
Telegram.PackageName = "Telegram Connector"
Telegram.downloadPath = getMudletHomeDir().."/telegram downloads/"
Telegram.Options = {}
Telegram.MyName = Telegram.MyName or getProfileName()
Telegram.UpdateInterval = Telegram.UpdateInterval or 10 -- seconds
Telegram.Enabled = Telegram.Enabled or true
Telegram.Enabled = true
Telegram.EventHandlerIds = Telegram.EventHandlerIds or {}
Telegram.AliasHandlerIds = Telegram.AliasHandlerIds or {}
Telegram.URL = "https://api.telegram.org/bot"
Telegram.getReturnHandler = Telegram.getReturnHandler or nil
Telegram.getUpdateTimerId = Telegram.getUpdateTimerId or nil
Telegram.LastIdHandled = Telegram.LastIdHandled or -1
--Telegram.LastIdHandled = -1
local URL_GETUPDATES=nil
local URL_SENDMESSAGE=nil
local lineBuffer = {}
local current_message_id = -1
local current_chat_id = -1
function Telegram:SaveConfig()
cecho("<cyan>Saving Telegram config...\n")
table.save(getMudletHomeDir().."/telegram_options.lua", Telegram.Options)
end
function Telegram:SetToken(token)
Telegram.Options["Token"] = token
Telegram:UpdateUrls()
end
function Telegram:checkVersion()
local path = Telegram.downloadPath .. "versions.lua"
local versions = {}
table.load(path, versions)
--display(versions)
local pos = table.index_of(versions, Telegram.Version) or 0
local line = ""
if pos ~= 1 then
line = "<orange>(online - ".. versions[1] ..")\n \t #TELEGRAM UPGRADE to upgrade"
else
line =""
end
return line
end
function Telegram:downloadVersionFile()
--print("Download the versions file")
if not io.exists(Telegram.downloadPath) then lfs.mkdir(Telegram.downloadPath) end
local filename = "versions.lua"
Telegram.downloading=true
--print("download "..url_versionDownload)
downloadFile(Telegram.downloadPath .. filename, url_versionDownload)
end
function Telegram:downloadLatestVersion()
cecho("<cyan>Downloading the latest version of "..Telegram.PackageName)
print()
if not io.exists(Telegram.downloadPath) then lfs.mkdir(Telegram.downloadPath) end
local filename = "TelegramConnector.mpackage"
Telegram.downloading=true
downloadFile(Telegram.downloadPath .. filename, url_latestVersion .. filename)
end
function Telegram:update_version()
print("Update the version")
--local path = profilePath .. "/map downloads/generic_mapper.xml"
--uninstallPackage("cpc") -- remove local instance (module)
--uninstallModule("cpc") -- remove local instance (module)
Telegram:killAllExistingEventHandlers()
uninstallPackage("Telegram Connector")
installPackage(Telegram.downloadPath .. "TelegramConnector.mpackage")
--installModule
end
function Telegram:UpdateUrls()
if Telegram.Options["Token"]~=nil then
URL_GETUPDATES=Telegram.URL..Telegram.Options.Token.."/getUpdates"
URL_SENDMESSAGE=Telegram.URL..Telegram.Options.Token.."/sendMessage"
end
end
function Telegram:LoadConfig()
if io.exists(getMudletHomeDir().."/telegram_options.lua") then
cecho("<cyan>Loading Telegram config...\n")
table.load(getMudletHomeDir().."/telegram_options.lua", Telegram.Options) -- using / is OK on Windows too.
else -- save it if it doesnt exits
cecho("<cyan>Creating new Telegram config...\n")
Telegram:DeleteConfig()
Telegram:SaveConfig()
Telegram:Reset()
end
Telegram:UpdateUrls()
end
function Telegram:HandleUserCommand(cmd,args)
--print("HandleUserCommand")
--display(cmd)
--display(args)
cmd = string.lower(cmd)
local cmdA = string.split(args," ")
sub_cmd = string.lower(table.remove(cmdA,1))
sub_args = table.concat(cmdA," ")
if (cmd=="help") then -- Hook to global #HELP
Telegram:showHelp()
elseif (cmd=="version") then -- Hook to global #VERSION
Telegram:showVersion()
elseif (cmd=="about") then -- Hook to global #ABOUT
Telegram:showAbout()
-- Package specific below
elseif (cmd=="telegram") then
if sub_cmd=="" then
Telegram:showHelp()
Telegram:showStatus()
elseif sub_cmd=="enable" then
Telegram.Enabled = true
cecho("<green>"..Telegram.PackageName.." ENABLED\n")
--Telegram:showStatus()
elseif sub_cmd=="disable" then
Telegram.Enabled = false
cecho("<orange>"..Telegram.PackageName.." DISABLED\n")
--Telegram:showStatus()
elseif sub_cmd=="version" then
Telegram:showVersion()
elseif sub_cmd=="help" then
Telegram:showHelp()
elseif sub_cmd=="about" then
Telegram:showAbout()
elseif sub_cmd=="status" then
Telegram:showStatus()
elseif sub_cmd=="delete" then
Telegram:DeleteConfig()
Telegram:SaveConfig()
Telegram:Reset()
elseif sub_cmd=="token" then
Telegram:SetToken(sub_args)
Telegram:CheckConfig()
Telegram:SaveConfig()
elseif sub_cmd=="auth" or sub_cmd=="authorize" then
Telegram:Authorize(sub_args)
elseif sub_cmd=="unauth" then
Telegram:UnAuthorize(sub_args)
elseif sub_cmd=="interval" then
Telegram:SetInterval(sub_args)
elseif sub_cmd=="tell" then
local msgA = string.split(sub_args," ")
local username = table.remove(msgA,1)
local msg = table.concat(msgA," ")
Telegram:Tell(username, msg)
elseif sub_cmd=="whisper" then
local msgA = string.split(sub_args," ")
local username = table.remove(msgA,1)
local msg = table.concat(msgA," ")
Telegram:Tell(username, msg, true)
elseif sub_cmd=="upgrade" then
Telegram:downloadLatestVersion()
end
--local subcmd =
end
end
function Telegram:showHelp()
cecho("<cyan>".. Telegram.PackageName ..":\n")
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#HELP"),"Show Helpfile(s)"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#VERSION"),"Show version(s)"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM STATUS"),"Show Telegram Status"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM TOKEN <token>"),"Set Telegram Token"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM UPGRADE"),"Upgrade the package"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM INTERVAL <seconds>"),"Set polling interval, default 10s"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM TELL <username> <message>"),"Send a message to a telegram user"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM WHISPER <username> <message>"),"Send a message to a telegram user (no notification)"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM ENABLE/DISABLE"),"Enable or Disable the package"))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM AUTH <name>"),"Authorize a Telegram user."))
cecho(string.format("<cyan>%-30s- %s\n",string.format(" %s","#TELEGRAM UNAUTH <name>"),"UnAuthorize a Telegram user."))
cecho("<cyan>---------------------------------------------------------------------------------------\n")
print()
end
function Telegram:showAbout()
print("Show about")
end
function Telegram:SetInterval(seconds)
local s = tonumber(seconds)
if s then
cecho("<green>Set Telegram polling inverval to "..s.." seconds\n")
Telegram.Options.Interval=s
Telegram:SaveConfig()
if Telegram.getUpdateTimerId~=nil then
killTimer(Telegram.getUpdateTimerId)
end
Telegram.getUpdateTimerId = tempTimer(Telegram.Options.Interval,[[Telegram:getUpdates()]],true)
else
cecho("<orange>'"..seconds.."' is not a valid interval...\n")
end
end
function Telegram:Authorize(name)
--print("authorize")
if Telegram.Options.PendingAuthorization[name]~=nil then
Telegram.Options.Authorized[name]=Telegram.Options.PendingAuthorization[name]
Telegram.Options.PendingAuthorization[name]=nil
cecho("<green>Authorized '"..name.."' for Telegram usage. You can now also send messages using\n")
cecho("<green>#TELEGRAM TELL "..name.." <message>\n")
Telegram.SaveConfig()
else
cecho("<orange>'"..name.."' not pending authorization, have him/her send a message to the bot first...\n")
end
end
function Telegram:UnAuthorize(name)
--print("authorize")
if Telegram.Options.Authorized[name]~=nil then
Telegram.Options.Authorized[name]= nil
Telegram.Options.PendingAuthorization[name]=nil
cecho("<green>UnAuthorized '"..name.."' for Telegram usage. \n")
Telegram.SaveConfig()
else
cecho("<orange>'"..name.."' not authorized, nothing done...\n")
end
end
function Telegram:showStatus()
cecho("<cyan>---------------------------- TELEGRAM CONNECTOR STATUS --------------------------------\n")
Telegram:showVersion()
cecho("<cyan>Token: '"..Telegram.Options["Token"].."'\n")
cecho("<cyan>Enabled: '"..tostring(Telegram.Options.Enabled).."'\n")
cecho("<cyan>Polling Interval: "..Telegram.Options.Interval.." seconds\n")
-- interval
-- last id handled
-- authorized
cecho("<cyan>Authorized:\n")
local countAuthorized =0
local countPending =0
for _ in pairs(Telegram.Options.Authorized) do countAuthorized = countAuthorized + 1 end
for _ in pairs(Telegram.Options.PendingAuthorization) do countPending = countPending + 1 end
if countAuthorized>0 then
for name,v in pairs(Telegram.Options.Authorized) do
cecho("\t<green>"..name.."\n")
end
else
cecho("\t<orange>NONE!\n")
end
-- pending authorization
if countPending>0 then
cecho("<cyan>Pending Authorization:\n")
for name,v in pairs(Telegram.Options.PendingAuthorization) do
cecho("\t<orange>"..name.."\n")
end
end
-- ignored
cecho("<cyan>---------------------------------------------------------------------------------------\n")
Telegram:Reset()
Telegram:CheckConfig()
Telegram:getUpdates()
end
function Telegram:showVersion()
--local vline = Telegram:checkVersion()
--cecho(string.format("<cyan>%-50s: %s %s\n","Cross Profile Communication",cpc.version,vline))
--cecho(string.format("<cyan>%-50s: %s\n","Telegram Connector",Telegram.Version))
local vline = Telegram:checkVersion()
cecho(string.format("<cyan>%-50s: %s %s\n",Telegram.PackageName,Telegram.Version,vline))
end
function Telegram:DeleteConfig()
cecho("<cyan>Deleting Telegram config...\n")
Telegram.Options = {}
Telegram.Options.Authorized={}
Telegram.Options.PendingAuthorization = {} -- populate from file
Telegram.Options.Enabled = true
Telegram.Options.Token=""
Telegram.Options.Interval=10
Telegram:UpdateUrls()
end
function Telegram:getInitialUpdates()
--getHTTP(Telegram.URL..Telegram.Token.."/getUpdates")
--print("getUpdates")
if Telegram.Options.Enabled and Telegram.Options.Token~="" then
--print("enabled, getUpdates")
getHTTP(URL_GETUPDATES)
end
end
function Telegram:getUpdates()
--getHTTP(Telegram.URL..Telegram.Token.."/getUpdates")
--print("getUpdates")
if Telegram.Options.Enabled and Telegram.Options.Token~="" then
--print("enabled, getUpdates")
--getHTTP(URL_GETUPDATES)
local header = {["Content-Type"] = "application/json"}
local opts = {}
opts["allowed_updates"] = {"message"}
if Telegram.LastIdHandled == -1 then
opts["offset"] = -2
else
opts["offset"] = Telegram.LastIdHandled+1
end
--opts["limit"] = 10
--display(opts)
postHTTP(yajl.to_string(opts),URL_GETUPDATES,header)
end
end
function Telegram:onHttpPost(event, ...)
if event=="sysPostHttpError" then
if string.find(arg[1],"telegram")~=nil then
display(arg)
end
else
local content = yajl.to_value(arg[2])
local url = arg[1] -- use this to check if this is a telegram message, and if so what type
local response = arg[3] -- not sure what to use this for
--if string.starts(url,Telegram.URL) then
if url:starts("https://api.telegram.org") then -- we only care about telegram messages
if url == URL_GETUPDATES then
--display(url)
--print("getUpdates!")
--display(content)
--display(content["ok"])
--display(content["result"])
if content["ok"] then
--print("content ok")
--display(content)
Telegram:ParseUpdates(content["result"])
--display("Parse done")
else
cecho("<orange>getUpdates was not successful, check URL\n")
display(arg)
end
end
end
end
--display(arg)
end
function Telegram:onHttpGetDone(event, ...)
--print("GetReturned")
--display(arg)
--display(arg[2])
local content = yajl.to_value(arg[2])
local url = arg[1] -- use this to check if this is a telegram message, and if so what type
local response = arg[3] -- not sure what to use this for
--display(event)
--display(url)
--if string.starts(url,Telegram.URL) then
if url:starts("https://api.telegram.org") then -- we only care about telegram messages
if url == URL_GETUPDATES then
--print("getUpdates!")
--display(content)
--display(content["ok"])
--display(content["result"])
if content["ok"] then
Telegram:ParseUpdates(content["result"])
else
cecho("<orange>getUpdates was not successful, check URL\n")
display(arg)
end
else
cecho("<orange>GET Not handled\n")
display(url)
display(contents)
end
end
end
function Telegram:Reset()
Telegram.LastIdHandled=-1
Telegram:UpdateUrls()
end
function Telegram:onFileDownloaded(event, ...)
--print("onFileDownloaded")
if event == "sysDownloadDone" and Telegram.downloading then
--print("check what type of file")
local file = arg[1]
--display(file)
--display(arg)
if string.ends(file,"/versions.lua") then
--print("Versions file downloaded from github")
Telegram.downloading=false
Telegram:checkVersion()
elseif string.ends(file,"/TelegramConnector.mpackage") then
--print("New version of Telegram downloaded...")
Telegram.downloading=false
Telegram:update_version()
end
end
end
function Telegram:ParseUpdates(contents)
--print("ParseUpdates")
--display(contents)
if Telegram.LastIdHandled==-1 then
print("just loaded, update lasthandled to..")
--display(contents[#contents])
--Telegram.LastIdHandled = contents[#contents]["message"]["message_id"]
for i,m in pairs(contents) do
if m["message"]~=nil then
if m["message"]["message_id"] then
Telegram.LastIdHandled = m["message"]["message_id"]
end
end
end
print("Last id handled set to:"..Telegram.LastIdHandled)
end
for i,m in pairs(contents) do
if m["message"]==nil then
--print("system message, ignore")
else
local t = m["message"]["chat"]["type"] -- private or group
local message_id = m["message"]["message_id"]
local chat_id = m["message"]["chat"]["id"]
local from_id = m["message"]["from"]["id"]
local sender_id = m["message"]["from"]["id"]
local cmd = m["message"]["text"]
local from_username = m["message"]["from"]["username"]
--print(t)
--print(message_id)
--print(channel_id)
--print(sender_id)
--print(cmd)
--print("have i handled this? "..message_id)
if message_id>Telegram.LastIdHandled then
--print("no")
--print(message_id.."/"..Telegram.LastIdHandled.." "..cmd)
if t=="group" then
-- is this message for me?
cmdA = cmd:split(" ")
local cmdName = string.lower(cmdA[1])
if string.find(cmdName,string.lower(Telegram.MyName))~=nil then
--print("This command is for me, execute it")
-- remove first word
--display(cmd)
--cmdA = string.split(cmd," ")
--display(cmdA)
table.remove(cmdA,1)
--display(cmdA)
cmd = table.concat(cmdA," ")
--Telegram:HandleCommand(cmd,message_id,chat_id)
else
print("This command is for '"..cmdName.."', i am '"..Telegram.MyName.."', Ignore it...")
cmd = nil
end
--print("Name")
--print(cmdA[1])
else
-- private message, just execute it
--Telegram:HandleCommand(cmd,message_id,chat_id)
end
if cmd~=nil then
--display("cmd not nil")
--display(from_username)
--display(Telegram:CheckAuthorized(from_username))
if Telegram:CheckAuthorized(from_username) then
Telegram:HandleCommand(cmd,message_id,chat_id,from_username)
else
--display(m)
cecho("<orange>Telegram (".. from_username .." UNAUTHORIZED) has asked me to: '"..cmd.."'\n")
cecho("<orange>#TELEGRAM AUTH "..from_username.." to authorize\n")
cecho("<orange>#TELEGRAM IGNORE "..from_username.." to ignore future requests\n")
-- add to pending approvals
Telegram.Options.PendingAuthorization[from_username]=from_id
--display(Telegram.Options.PendingAuthorization)
local msg = "<b>"..Telegram:HtmlEncode("Command ignored....\nUser '"..from_username.."' not authorized\n#TELEGRAM AUTH "..from_username.." in Mudlet to Authorize.").."</b>"
local retMsg = {}
retMsg["chat_id"]=chat_id
retMsg["text"]=msg
retMsg["reply_to_message_id"]=message_id
retMsg["disable_notification"]=true
retMsg["parse_mode"]="HTML"
current_message_id = message_id
current_chat_id = chat_id
--local header = {["Content-Type"] = "application/json"}
--postHTTP(yajl.to_string(retMsg),URL_SENDMESSAGE,header)
Telegram:SendMessage(retMsg)
Telegram.LastIdHandled = message_id
end
else
-- just update the id
Telegram.LastIdHandled = message_id
end
end
end
end
end
function Telegram:HtmlEncode(str)
str = string.gsub(str,"&","&amp;")
str = string.gsub(str,"<","&lt;")
str = string.gsub(str,">","&gt;")
return str
end
function Telegram:CaptureLine(...)
if isPrompt() then
killTrigger(Telegram.lineTriggerId)
Telegram.lineTriggerId = nil
--display(lineBuffer)
local htmlMsg = Telegram:HtmlEncode(table.concat(lineBuffer,"\n"))
local retMsg = {}
retMsg["chat_id"]=current_chat_id
--retMsg["text"]="<pre>"..table.concat(lineBuffer,"\n").."</pre>"
retMsg["text"]="<pre>"..htmlMsg.."</pre>"
retMsg["reply_to_message_id"]=current_message_id
retMsg["disable_notification"]=true
retMsg["parse_mode"]="HTML"
--local header = {["Content-Type"] = "application/json"}
--postHTTP(yajl.to_string(retMsg),URL_SENDMESSAGE,header)
Telegram:SendMessage(retMsg)
else
-- dont add prompt
table.insert(lineBuffer,line)
end
end
function Telegram:Tell(username,msg,disable_notification)
--print("try to send message to telegram...")
disable_notification = disable_notification or false
--display(username)
--display(msg)
if Telegram.Options.Authorized[username]~=nil then
local htmlMsg = Telegram:HtmlEncode(msg)
local retMsg = {}
retMsg["chat_id"]=Telegram.Options.Authorized[username]
--retMsg["text"]="<pre>"..table.concat(lineBuffer,"\n").."</pre>"
--retMsg["text"]="<pre>"..htmlMsg.."</pre>"
retMsg["text"]=msg
--retMsg["reply_to_message_id"]=current_message_id
retMsg["disable_notification"]= disable_notification
--retMsg["parse_mode"]="HTML"
--display(retMsg)
Telegram:SendMessage(retMsg)
else
cecho("<orange>'"..username.."' is not authorized, use:\n")
cecho("<orange>#TELEGRAM AUTH "..username.."\n")
end
end
function Telegram:SendMessage(msgTable)
local header = {["Content-Type"] = "application/json"}
Telegram:UpdateUrls()
--print("url: "..URL_SENDMESSAGE)
cecho("<cyan>Sending to telegram...\n")
postHTTP(yajl.to_string(msgTable),URL_SENDMESSAGE,header)
end
function Telegram:CheckConfig()
if Telegram.Options["Token"]=="" then
cecho("<orange>Token has not been set.\n")
cecho("<orange>#TELEGRAM TOKEN <token> to set..\n")
end
local countAuthorized = 0
for _ in pairs(Telegram.Options.Authorized) do countAuthorized = countAuthorized + 1 end
if countAuthorized==0 then
cecho("<orange>No one has been authorized. Send a message to the bot from Telegram, then!\n")
cecho("<orange>#TELEGRAM AUTH <charname>\n")
end
end
function Telegram:CheckAuthorized(from_username)
if Telegram.Options.Authorized[from_username]==nil then
return false
else
return true
end
end
function Telegram:HandleCommand(cmd,message_id,chat_id,from_username)
-- check if Authorized
--print("check if "..from_username.." is authorized...")
--display(Telegram.Authorized)
--display(Telegram.Authorized[from_username])
-- notify "On It"
cecho("<cyan>Telegram (".. from_username ..") has asked me to: '"..cmd.."'\n")
local retMsg = {}
retMsg["chat_id"]=chat_id
retMsg["text"]="on it"
retMsg["reply_to_message_id"]=message_id
retMsg["disable_notification"]=true
current_message_id = message_id
current_chat_id = chat_id
--local header = {["Content-Type"] = "application/json"}
--postHTTP(yajl.to_string(retMsg),URL_SENDMESSAGE,header)
Telegram:SendMessage(retMsg)
-- start capture
lineBuffer = {}
-- enable line trigger
if Telegram.lineTriggerId then
killTrigger(Telegram.lineTriggerId)
Telegram.lineTriggerId = nil
end
Telegram.lineTriggerId = tempLineTrigger(0,99,[[Telegram:CaptureLine()]])
-- send command
expandAlias(cmd)
-- update last handled
Telegram.LastIdHandled = message_id
-- stop Capture
-- send last 3 lines back
return true
end
function Telegram:killAllExistingEventHandlers()
-- kill all dynamic handlers
-- ... events
for i,handlerId in pairs(Telegram.EventHandlerIds) do
if tonumber(handlerId) then
killAnonymousEventHandler(handlerId)
Telegram.EventHandlerIds[i]= nil
end
end
-- ... Aliases
for i,handlerId in pairs(Telegram.AliasHandlerIds) do
--print("Should remove alias "..handlerId)
if tonumber(handlerId) then
killAlias(handlerId)
Telegram.AliasHandlerIds[i]= nil
end
end
if Telegram.getReturnHandler~=nil then
killAnonymousEventHandler(Telegram.getReturnHandler)
end
if Telegram.getUpdateTimerId~=nil then
killTimer(Telegram.getUpdateTimerId)
end
end
-- =========================================
-- INIT
-- =========================================
Telegram:killAllExistingEventHandlers()
-- setup dynamic eventHandlers
table.insert(Telegram.EventHandlerIds,registerAnonymousEventHandler("sysPostHttpDone", [[Telegram:onHttpPost]]))
table.insert(Telegram.EventHandlerIds,registerAnonymousEventHandler("sysPostHttpError", [[Telegram:onHttpPost]]))
table.insert(Telegram.EventHandlerIds,registerAnonymousEventHandler("sysDownloadDone", [[Telegram:onFileDownloaded]]))
table.insert(Telegram.AliasHandlerIds,tempAlias([[^#(?i)(\btelegram\b|\bhelp\b|\bversion\b|\babout\b)(?-i)\s*(.*)$]],[[Telegram:HandleUserCommand(matches[2],matches[3])]]))
for i,handlerId in pairs(Telegram.AliasHandlerIds) do
--print("Should remove alias "..handlerId)
if tonumber(handlerId) then
enableAlias(handlerId)
end
end
-- manual handlers
Telegram.getReturnHandler = registerAnonymousEventHandler("sysGetHttpDone", [[Telegram:onHttpGetDone]])
Telegram:downloadVersionFile()
Telegram:LoadConfig()
Telegram.getUpdateTimerId = tempTimer(Telegram.Options.Interval,[[Telegram:getUpdates()]],true)
Telegram:CheckConfig()
--Telegram:CheckVersion()
--display(Telegram.Options)
Telegram:getInitialUpdates()</script>
<eventHandlerList />
</Script>
</ScriptPackage>
<KeyPackage />
<HelpPackage>
<helpURL></helpURL>
</HelpPackage>
</MudletPackage>