-
Notifications
You must be signed in to change notification settings - Fork 13
/
50_TelegramBot.pm
4344 lines (3374 loc) · 171 KB
/
50_TelegramBot.pm
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# 50_TelegramBot.pm
#
# This file is part of Fhem.
#
# Fhem is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Fhem is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fhem. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#
# TelegramBot (c) Johannes Viegener / https://github.com/viegener/Telegram-fhem
#
# This module handles receiving and sending messages to the messaging service telegram (see https://telegram.org/)
# TelegramBot is making use of the Telegrom Bot API (see https://core.telegram.org/bots and https://core.telegram.org/bots/api)
# For using it with fhem an telegram BOT API key is needed! --> see https://core.telegram.org/bots/api#authorizing-your-bot
#
# Discussed in FHEM Forum: https://forum.fhem.de/index.php/topic,38328.0.html
#
# $Id: 50_TelegramBot.pm 22708 2020-09-01 15:51:38Z viegener $
#
#
##############################################################################
# 0.0 2015-09-16 Started
# 1.0 2015-10-17 Initial SVN-Version
# 2.0 2016-10-19 multibot support / markup on send text / msgEdit
# disable_web_page_preview - attribut webPagePreview - msg506924
# log other messages in getupdate
# add new get command "update" for single update poll
# new cmd for forcing a msg reply - msgForceReply
# add readings for reply msg id: msgReplyMsgId
# documemt: msgForceReply, msgReplyMsgId
# diable attribute to stop polling
# keyboards through [] in message command(s) -> no changed to () to avoid issues
# send incomplete keyboards as message instead of error
# Add | as separator for keys
# documentation alignment - more consistent usage of peer (instead of user)
# Keyboards in () istead of []
# added callback being retrieved in updates
# allow inline keyboards sent - new command inline keys titel:data
# allow answer to callback (id must be given / text is optional)
# document inline / answer
# cleaned up recommendations for cmdKeyword etc
# corrections to doc and code - msg540802
# command names for answer / inline -changed to-> queryInline, queryAnswer - msg540802
# attribute for automatic answer - eval set logic - queryAnswerText
# FIX: trim $ret avoiding empty msg error from telegram in command response
# FIX: trim $ret avoiding empty msg error from telegram also with control characters in 2 chars
# rename callback... readings to query... for consistency
# value 0 for queryAnswerText means no text sent but still answer
# FIX: corrected documentation - unbalanced li
# Run set magic on all comands before execution
# add new reading sentMsgPeerId
# add edit message for inline keyboards?
# document queryEditInline
# "0" message still sent on queryanswer
# 2.1 2016-12-25 msgForceReply, disable, keyboards in messages, inline keyboards and dialogs
# allow response for commands being sent in chats - new attribute cmdRespondChat to configure
# new reading msgChatId
# exclamation mark in favorites to allow empty results also being sent
# new get peerID for onverting a named peer into an id (same syntax as in msg)
# document get commands
# communication with TBot_List Module -> queryAnswer
# document cmdRespondChat / msgChatId
# "Bad Request:" or "Unauthorized" do not result in retry
# cleaned up done list
# ATTENTION: store api key in setkey value see patch from msg576714
# put values in chat/chatId even if no group involved (peer will be set)
# 2.2 2017-02-26 msgChatId with peer / api key secured / communication with TBot_List
# cmdSend to send the result of a command as message (used for sending SVGs)
# add utf8Special attribute for encoding before send
# reset msgReplyMsgId on reception to empty if no replyid
# clarified scope of cmdRestrictedPeer in doc
# changed utf8Special to downgrade
# FIX: defpeer undefined in #msg605605
# FIXDOC: url escaping for filenames
# avoid empty favorites
# allow multiple commands in favorites with double ;;
# DOC: multiple commands in favorites
# allow flagging favorites not shown in favlist (only with alias prefixing alias with a hyphen --> /-alias )
# FIX: Allow utf8 again
# alias execution is not honoring needsconfirm and sent result --> needs to be backward compatible
# cleanup for favorite execution and parsing
# reduce utf8 handling
# add favorite hidden zusatz
# favorite keyboard 2 column #msg609128
# 2.3 2017-03-27 utf8Special for unicode issues / favorite handling / hidden favorites
# doc: favorites2Col for 2 columns favorites keyboard
# fix: aliasExec can be undefined - avoid error
# allow : in keyboards (either escaped or just use last : for data split) --> #msg611609
# allow space before = in favorite
# favoritesInline attribute for having favorites handled with inline keyboards
# INT: addtl Parameter in SendIt for options (-msgid-)
# Handle favorites as inline
# document favoritesInline
# remove old inline favorites dialog on execution of commands
# allow execution of hidden favorites from inline menu
# Debug/log cleanup
# 2.4 2017-05-25 favorites rework - inline / allow : in inline
# fix: options remove in sendit corrected: #msg641797
# DOCFIX: Double semicolon for multiple commands in favorites
# FIX: non-local $_ - see #msg647071
# 2.4.1 2017-06-16 minor fixes - #msg641797 / #msg647071
# FIX: make fileread work for both old and new perl versions
# 2.4.2 2017-07-01 rewrite read file function due to $_ warning - #msg651947
# FIX: make delayed retry work again
# rename of bot also works with token encryption - #msg668108
# 2.4.3 2017-08-13 delayed retry & rename (#msg668108)
# remove debug / addtl testing
# adapt prototypes for token
# additional logs / removed debugs
# special httputils debug lines added
# add msgDelete function to delete messages sent before from the bot
# added check for msgId not given as first parameter (e.g. msgDelete / msgEdit)
# 2.5 2017-09-10 new set cmd msgDelete
# add - in description will not show favorite command in menu #msg686352
# Issue: when direct favorite confirm is cancelled - do not jump to favorite menu
# json_decode mit nonref #msg687580
# 2.6 2017-09-24 hide command in favorites/change direct favorites confirm
# Fix minusdesc undefined issue
# Cleanup old code
# add favoritesMenu to send favorites
# doc favoritesMenu
# correct favoritesMenu to allow parameter
# FIX: allow_nonref / eval also for makekeyboard #msg732757
# new set cmd silentmsg for disable_notification - syntax as in msg
# INT: change forceReply to options for sendit
# 2.7 2017-12-20 set command silentmsg
# new set cmd silentImage for disable_notification - syntax as in sendImage
# FIX: allow queryAsnwer also with defaultpeer not set #msg757339
# General. set commands not requiring a peer - internally set peers to 0 for sendit
# FIX: Doc missing end code tag
# Change log to not write _Set/_Get on ? parameter
# attr to handle set / del types for polling/allowedCmds/favorites
# silentInline added
# cmdSendSilent added and documented
# tests and fixes on handling of peers/chats for tbot_list and replies
# FIX: peer names not numeric in send commands
# FIX: disable also sending messages
# FIX: have disable attribute with dropdown
# Allow caption in sendImage also with \n\t
# 2.8 2018-03-11 more silent cmds, caption formatting, several fixes
# Pull request: silentDocument, silentLocation, silentVoice
# Corrections for single peer not needed for sent command
# single peer limited for reply and other change messages
# Allow \s for space in message (allows multiple spaces in preformatted messages)
# Document \n \t \s in messages
# Corrected Eol
# 2.9 2019-05-23 allow \s, addtl silenCmds, fixes
# FIX: correct parsemodesend for inMsg with multiple lines - msg1041326
#
# TelegramBot_Callback add support for channel messages and edit
# Add contact support for channels
# add version id as internal - sourceVersion
# New attr allowChannels for allowing channel messages explicitely
# check command handing for channels
# remove keyboard after favorite confirm
# replyKeyboardRemove - #msg592808
# replace single semicolons in favorites (with double semicolons) - msg1078989
# FIX: answercallback always if querydata is set
# Add new sendformat video to set - cmd sendVideo / silentVideo
# Recognize stream of video format (esp. mp4 - needs testing)
# recognize stream isMedia with negative numbers
# document video commands
#SVN 21.10.2020
# Also support edited_message updates
# check parseMsg if $from not there --> log then
# removed new_chat_participant
# log all new contacts - with source
# #msg1168649: Corrected logging verbose to make 0_None work
# caption parseMode / formatting also available for photo and video sends
# avoid warning for incomplete msgDelete commands
# replaceSetMagic on favorites not done before execution
# add reading msgDate
# update documentation
# Fix: error msg on empty favoritedef
# Attribute deleteResponseMessage to delete message at the end insteda of sending "-" / "Favoriten beendet" --> msg1133794
# change doc to allow inline help for set/attr
# add get commands id to ensure showin in UI
# add description of pollingtimeout - needing update
# MarkdownV2 as new option (also new option for parsemodeSend MarkdownV1 for legacy support - currently markdown is still v1)
# documented markdownV2
# cleaned up documentation formatting
#
#
##############################################################################
# TASKS
#
#
# Restructure help in logical blocks
#
# queryDialogStart / queryDialogEnd - keep msg id
#
# cleanup encodings
#
#
##############################################################################
package main;
use strict;
use warnings;
use HttpUtils;
use utf8;
use Encode;
# JSON:XS is used here normally
use JSON;
use File::Basename;
use URI::Escape;
use Scalar::Util qw(reftype looks_like_number);
use DevIo;
#########################
# Forward declaration
sub TelegramBot_Define($$);
sub TelegramBot_Undef($$);
sub TelegramBot_Set($@);
sub TelegramBot_Get($@);
sub TelegramBot_Callback($$$);
sub TelegramBot_SendIt($$$$$;$$$);
sub TelegramBot_checkAllowedPeer($$$);
sub TelegramBot_SplitFavoriteDef($$);
sub TelegramBot_AttrNum($$$);
sub TelegramBot_MakeKeyboard($$$@);
sub TelegramBot_ExecuteCommand($$$$;$$);
sub TelegramBot_readToken($;$);
sub TelegramBot_storeToken($$;$);
#########################
# Globals
my $repositoryID = '$Id: 50_TelegramBot.pm 22708 2020-09-01 15:51:38Z viegener $';
my %sets = (
"_msg" => "textField",
"message" => "textField",
"msg" => "textField",
"send" => "textField",
"silentmsg" => "textField",
"silentImage" => "textField",
"silentInline" => "textField",
"silentDocument" => "textField",
"silentLocation" => "textField",
"silentVoice" => "textField",
"silentVideo" => "textField",
"msgDelete" => "textField",
"msgEdit" => "textField",
"msgForceReply" => "textField",
"queryAnswer" => "textField",
"queryInline" => "textField",
"queryEditInline" => "textField",
"sendImage" => "textField",
"sendPhoto" => "textField",
"sendDocument" => "textField",
"sendMedia" => "textField",
"sendVoice" => "textField",
"sendVideo" => "textField",
"sendLocation" => "textField",
"favoritesMenu" => "textField",
"cmdSend" => "textField",
"cmdSendSilent" => "textField",
"replaceContacts" => "textField",
"reset" => undef,
"reply" => "textField",
"token" => "textField",
"zDebug" => "textField"
);
my %deprecatedsets = (
"image" => "textField",
"sendPhoto" => "textField",
);
my %gets = (
"urlForFile" => "textField",
"update" => undef,
"peerId" => "textField",
);
my $TelegramBot_header = "agent: TelegramBot/1.0\r\nUser-Agent: TelegramBot/1.0\r\nAccept: application/json\r\nAccept-Charset: utf-8";
my $TelegramBot_arg_retrycnt = 6;
##############################################################################
##############################################################################
##
## Module operation
##
##############################################################################
##############################################################################
#####################################
# Initialize is called from fhem.pl after loading the module
# define functions and attributed for the module and corresponding devices
sub TelegramBot_Initialize($) {
my ($hash) = @_;
$hash->{DefFn} = "TelegramBot_Define";
$hash->{UndefFn} = "TelegramBot_Undef";
$hash->{StateFn} = "TelegramBot_State";
$hash->{GetFn} = "TelegramBot_Get";
$hash->{RenameFn} = "TelegramBot_Rename";
$hash->{SetFn} = "TelegramBot_Set";
$hash->{AttrFn} = "TelegramBot_Attr";
$hash->{AttrList} = "defaultPeer defaultPeerCopy:0,1 cmdKeyword cmdSentCommands favorites:textField-long favoritesInline:0,1 cmdFavorites cmdRestrictedPeer ". "cmdTriggerOnly:0,1 saveStateOnContactChange:1,0 maxFileSize maxReturnSize cmdReturnEmptyResult:1,0 pollingVerbose:1_Digest,2_Log,0_None ".
"cmdTimeout pollingTimeout disable:1,0 queryAnswerText:textField cmdRespondChat:0,1 ".
"allowUnknownContacts:1,0 textResponseConfirm:textField textResponseCommands:textField allowedCommands filenameUrlEscape:1,0 ".
"textResponseFavorites:textField textResponseResult:textField textResponseUnauthorized:textField ".
"deleteResponseMessage:0,1 ".
"parseModeSend:0_None,1_Markdown,2_HTML,3_InMsg,4_MarkdownV1,5_MarkdownV2 webPagePreview:1,0 utf8Special:1,0 favorites2Col:0,1 ".
" maxRetries:0,1,2,3,4,5 allowChannels:0,1 ".$readingFnAttributes;
}
######################################
# Define function is called for actually defining a device of the corresponding module
# For TelegramBot this is mainly API id for the bot
# data will be stored in the hash of the device as internals
#
sub TelegramBot_Define($$) {
my ($hash, $def) = @_;
my @a = split("[ \t]+", $def);
my $name = $hash->{NAME};
Log3 $name, 3, "TelegramBot_Define $name: called ";
my $errmsg = '';
# Check parameter(s)
# If api token is given check for syntax and remove from hash
if ( ( int(@a) == 3 ) && ( $a[2] !~ /^([[:alnum:]]|[-:_])+[[:alnum:]]+([[:alnum:]]|[-:_])+$/ ) ) {
$errmsg = "specify valid API token containing only alphanumeric characters and -: characters: define <name> TelegramBot [ <APItoken> ]";
Log3 $name, 1, "TelegramBot $name: " . $errmsg;
return $errmsg;
} elsif ( ( int(@a) == 2 ) && ( ! TelegramBot_readToken($hash) ) ){
$errmsg = "no predefined token found specify token in define: define <name> TelegramBot <APItoken>";
Log3 $name, 1, "TelegramBot $name: " . $errmsg;
return $errmsg;
} elsif( int(@a) > 3 || int(@a) < 2) {
$errmsg = "syntax error: define <name> TelegramBot [ <APIid> ]";
Log3 $name, 1, "TelegramBot $name: " . $errmsg;
return $errmsg;
}
my $ret;
$hash->{TYPE} = "TelegramBot";
$hash->{STATE} = "Undefined";
$hash->{WAIT} = 0;
$hash->{FAILS} = 0;
$hash->{UPDATER} = 0;
$hash->{POLLING} = -1;
my %hu_upd_params = (
url => "",
timeout => 5,
method => "GET",
header => $TelegramBot_header,
isPolling => "update",
hideurl => 1,
callback => \&TelegramBot_Callback
);
my %hu_do_params = (
url => "",
timeout => 30,
method => "GET",
header => $TelegramBot_header,
hideurl => 1,
callback => \&TelegramBot_Callback
);
$hash->{HU_UPD_PARAMS} = \%hu_upd_params;
$hash->{HU_DO_PARAMS} = \%hu_do_params;
if (int(@a) == 3) {
TelegramBot_storeToken($hash, $a[2]);
$hash->{DEF} = undef;
}
TelegramBot_Setup( $hash );
return $ret;
}
#####################################
# Undef function is corresponding to the delete command the opposite to the define function
# Cleanup the device specifically for external ressources like connections, open files,
# external memory outside of hash, sub processes and timers
sub TelegramBot_Undef($$)
{
my ($hash, $arg) = @_;
my $name = $hash->{NAME};
Log3 $name, 3, "TelegramBot_Undef $name: called ";
HttpUtils_Close($hash->{HU_UPD_PARAMS});
HttpUtils_Close($hash->{HU_DO_PARAMS});
RemoveInternalTimer($hash);
RemoveInternalTimer($hash->{HU_DO_PARAMS});
Log3 $name, 4, "TelegramBot_Undef $name: done ";
return undef;
}
#############################################################################################
# called when the device gets renamed,
# in this case we then also need to rename the key in the token store and ensure it is recoded with new name
sub TelegramBot_Rename($$) {
my ($new,$old) = @_;
my $nhash = $defs{$new};
my $token = TelegramBot_readToken( $nhash, $old );
TelegramBot_storeToken( $nhash, $token );
# remove old token with old name
my $index_old = "TelegramBot_" . $old . "_token";
setKeyValue($index_old, undef);
}
##############################################################################
##############################################################################
##
## Instance operational methods
##
##############################################################################
##############################################################################
####################################
# State function to ensure contacts internal hash being reset on Contacts Readings Set
sub TelegramBot_State($$$$) {
my ($hash, $time, $name, $value) = @_;
# Log3 $hash->{NAME}, 4, "TelegramBot_State called with :$name: value :$value:";
if ($name eq 'Contacts') {
TelegramBot_CalcContactsHash( $hash, $value );
Log3 $hash->{NAME}, 4, "TelegramBot_State Contacts hash has now :".scalar(keys %{$hash->{Contacts}}).":";
}
return undef;
}
####################################
# set function for executing set operations on device
sub TelegramBot_Set($@)
{
my ( $hash, $name, @args ) = @_;
Log3 $name, 5, "TelegramBot_Set $name: called ";
### Check Args
my $numberOfArgs = int(@args);
return "TelegramBot_Set: No cmd specified for set" if ( $numberOfArgs < 1 );
my $cmd = shift @args;
if (!exists($sets{$cmd})) {
my @cList;
foreach my $k (keys %sets) {
my $opts = undef;
$opts = $sets{$k};
if (defined($opts)) {
push(@cList,$k . ':' . $opts);
} else {
push (@cList,$k);
}
} # end foreach
return "TelegramBot_Set: Unknown argument $cmd, choose one of " . join(" ", @cList);
} # error unknown cmd handling
Log3 $name, 4, "TelegramBot_Set $name: Processing TelegramBot_Set( $cmd )";
my $ret = undef;
if( ($cmd eq 'message') || ($cmd eq 'queryInline') || ($cmd eq 'queryEditInline') || ($cmd eq 'queryAnswer') ||
($cmd eq 'msg') || ($cmd eq '_msg') || ($cmd eq 'reply') || ($cmd eq 'msgEdit') || ($cmd eq 'msgForceReply') ||
($cmd =~ /^silent.*/ ) || ($cmd =~ /^send.*/ ) ) {
my $msgid;
my $msg;
my $addPar;
my $sendType = 0;
my $options = "";
my $peers;
my $inline = 0;
my $needspeer = 1;
my $singlepeer = 0;
if ( ($cmd eq 'reply') || ($cmd eq 'msgEdit' ) || ($cmd eq 'queryEditInline' ) ) {
return "TelegramBot_Set: Command $cmd, no msgid and no text/file specified" if ( $numberOfArgs < 3 );
$msgid = shift @args;
return "TelegramBot_Set: Command $cmd, msgId must be given as first parameter before peer" if ( $msgid =~ /^@/ );
$numberOfArgs--;
# all three messages need also a peer/chat_id
# but only a single peer is needed
$singlepeer = 1;
} elsif ($cmd eq 'queryAnswer') {
$needspeer = 0;
}
# special options
$inline = 1 if ( ($cmd eq 'queryInline') || ($cmd eq 'queryEditInline') || ($cmd eq 'silentInline') );
$options .= " -force_reply- " if ($cmd eq 'msgForceReply');
$options .= " -silent- " if ( ($cmd =~ /^silent.*/ ) ) ;
return "TelegramBot_Set: Command $cmd, no peers and no text/file specified" if ( $numberOfArgs < 2 );
# numberOfArgs might not be correct beyond this point
while ( $args[0] =~ /^@(..+)$/ ) {
my $ppart = $1;
return "TelegramBot_Set: Command $cmd, need exactly one peer" if ( ($singlepeer) && ( defined( $peers ) ) );
$peers .= " " if ( defined( $peers ) );
$peers = "" if ( ! defined( $peers ) );
$peers .= $ppart;
shift @args;
last if ( int(@args) == 0 );
}
return "TelegramBot_Set: Command $cmd, no msg content specified" if ( int(@args) < 1 );
if ( ($needspeer ) && ( ! defined( $peers ) ) ) {
$peers = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peers) );
} elsif ( ! defined( $peers ) ) {
$peers = 0;
}
if ( ($cmd eq 'sendPhoto') || ($cmd eq 'sendImage') || ($cmd eq 'image') || ($cmd eq 'silentImage') ) {
$sendType = 1;
} elsif ( ($cmd eq 'sendVoice') || ($cmd eq 'silentVoice') ) {
$sendType = 2;
} elsif ( ($cmd eq 'sendDocument') || ($cmd eq 'sendMedia') || ($cmd eq 'silentDocument') ) {
$sendType = 3;
} elsif ( ($cmd eq 'sendVideo') || ($cmd eq 'silentVideo') ) {
$sendType = 4;
} elsif ( ($cmd eq 'msgEdit') || ($cmd eq 'queryEditInline') ) {
$sendType = 10;
} elsif ( ($cmd eq 'sendLocation') || ($cmd eq 'silentLocation') ) {
$sendType = 11;
} elsif ($cmd eq 'queryAnswer') {
$sendType = 12;
}
if ( $sendType == 11 ) {
# location
return "TelegramBot_Set: Command $cmd, 2 parameters latitude / longitude need to be specified" if ( int(@args) != 2 );
# first latitude
$msg = shift @args;
# first longitude
$addPar = shift @args;
} elsif ( $sendType == 12 ) {
# inline query
return "TelegramBot_Set: Command $cmd, no inline query id given" if ( int(@args) < 1 );
# first inline query id
$addPar = shift @args;
# remaining msg
$msg = "";
$msg = join(" ", @args ) if ( int(@args) > 0 );
} elsif ( ( $sendType > 0 ) && ( $sendType < 10 ) ) {
# should return undef if succesful
$msg = shift @args;
$msg = $1 if ( $msg =~ /^\"(.*)\"$/ );
if ( ( $sendType == 1 ) || ( $sendType == 4 ) ) {
# for Photos and Videos a caption can be given (all content after file)
$addPar = join(" ", @args ) if ( int(@args) > 0 );
} else {
return "TelegramBot_Set: Command $cmd, extra parameter specified after filename" if ( int(@args) > 0 );
}
} else {
if ( ! defined( $addPar ) ) {
# check for Keyboard given (only if not forcing reply) and parse it to keys / jsonkb
my $onetime = 1;
my @keys;
if ( $args[0] =~ /^\s*\(\)\s*$/ ) {
Log3 $name, 4, "TelegramBot_Set $name: empty keys remove keyboard";
shift @args;
$onetime = 0;
} else {
while ( $args[0] =~ /^\s*\(.*$/ ) {
my $aKey = "";
while ( $aKey !~ /^\s*\((.*)\)\s*$/ ) {
$aKey .= " ".$args[0];
shift @args;
last if ( int(@args) == 0 );
}
# trim key
$aKey =~ s/^\s+|\s+$//g;
if ( $aKey =~ /^\((.*)\)$/ ) {
my @tmparr = split( /\|/, $1 );
push( @keys, \@tmparr );
} else {
# incomplete key handle as message
unshift( @args, $aKey ) if ( length( $aKey ) > 0 );
last;
}
}
}
$addPar = TelegramBot_MakeKeyboard( $hash, $onetime, $inline, @keys ) if ( ( scalar( @keys ) ) || ( $onetime == 0) );
}
return "TelegramBot_Set: Command $cmd, no text for msg specified " if ( int(@args) == 0 );
$msg = join(" ", @args );
}
Log3 $name, 5, "TelegramBot_Set $name: start send for cmd :$cmd: and sendType :$sendType:";
$ret = TelegramBot_SendIt( $hash, $peers, $msg, $addPar, $sendType, $msgid, $options );
} elsif($cmd eq 'favoritesMenu') {
my $peers;
if ( int(@args) > 0 ) {
while ( $args[0] =~ /^@(..+)$/ ) {
my $ppart = $1;
return "TelegramBot_Set: Command $cmd, need exactly one peer" if ( ( defined( $peers ) ) );
$peers = (defined($peers)?$peers." ":"").$ppart;
shift @args;
last if ( int(@args) == 0 );
}
return "TelegramBot_Set: Command $cmd, addiitonal parameter specified" if ( int(@args) >= 1 );
}
if ( ! defined( $peers ) ) {
$peers = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peers) );
}
return "TelegramBot_Set: Command $cmd, no favorites defined" if ( ! defined( AttrVal($name,'favorites',undef) ) );
TelegramBot_SendFavorites($hash, $peers, undef, "", undef, undef, 0);
} elsif($cmd =~ 'cmdSend(Silent)?') {
return "TelegramBot_Set: Command $cmd, no peers and no text/file specified" if ( $numberOfArgs < 2 );
# numberOfArgs might not be correct beyond this point
my $options = "";
$options .= " -silent- " if ( ($cmd eq 'cmdSendSilent') ) ;
my $peers;
while ( $args[0] =~ /^@(..+)$/ ) {
my $ppart = $1;
$peers .= " " if ( defined( $peers ) );
$peers = "" if ( ! defined( $peers ) );
$peers .= $ppart;
shift @args;
last if ( int(@args) == 0 );
}
return "TelegramBot_Set: Command $cmd, no msg content specified" if ( int(@args) < 1 );
if ( ! defined( $peers ) ) {
$peers = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peers) );
}
# Execute command
my $isMediaStream = 0;
my $msg;
my $scmd = join(" ", @args );
# run replace set magic on command - first
my %dummy;
my ($err, @a) = ReplaceSetMagic(\%dummy, 0, ( $scmd ) );
if ( $err ) {
Log3 $name, 1, "TelegramBot_Set $name: parse cmd failed on ReplaceSetmagic with :$err: on :$scmd:";
} else {
$msg = join(" ", @a);
Log3 $name, 4, "TelegramBot_Set $name: parse cmd returned :$msg:";
}
$msg = AnalyzeCommandChain( $hash, $msg );
# Check for image/doc/audio stream in return (-1 image
( $isMediaStream ) = TelegramBot_IdentifyStream( $hash, $msg ) if ( defined( $msg ) );
Log3 $name, 5, "TelegramBot_Set $name: start send for cmd :$cmd: and isMediaStream :$isMediaStream:";
$ret = TelegramBot_SendIt( $hash, $peers, $msg, undef, $isMediaStream, undef, $options );
} elsif($cmd eq 'msgDelete') {
my $peers;
my $sendType = 20;
return "TelegramBot_Set: Command $cmd, no peer and no msgid specified" if ( $numberOfArgs < 2 );
my $msgid = shift @args;
return "TelegramBot_Set: Command $cmd, msgId must be given as first parameter before peer" if ( $msgid =~ /^@/ );
$numberOfArgs--;
if ( int(@args) > 0 ) {
while ( $args[0] =~ /^@(..+)$/ ) {
my $ppart = $1;
return "TelegramBot_Set: Command $cmd, need exactly one peer" if ( defined( $peers ) );
$peers .= " " if ( defined( $peers ) );
$peers = "" if ( ! defined( $peers ) );
$peers .= $ppart;
shift @args;
last if ( int(@args) == 0 );
}
}
if ( ! defined( $peers ) ) {
$peers = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peers) );
}
Log3 $name, 5, "TelegramBot_Set $name: start send for cmd :$cmd: and sendType :$sendType:";
$ret = TelegramBot_SendIt( $hash, $peers, "", undef, $sendType, $msgid );
} elsif($cmd eq 'zDebug') {
# for internal testing only
Log3 $name, 5, "TelegramBot_Set $name: start debug option ";
# delete $hash->{sentMsgPeer};
# $ret = TelegramBot_SendIt( $hash, AttrVal($name,'defaultPeer',undef), "abc def\n def ghi", undef, 0, undef );
$hash->{HU_UPD_PARAMS}->{callback} = \&TelegramBot_Callback;
$hash->{HU_DO_PARAMS}->{callback} = \&TelegramBot_Callback;
} elsif($cmd eq 'token') {
if ( $numberOfArgs == 2 ) {
$ret = TelegramBot_storeToken ( $hash, $args[0] );
TelegramBot_Setup( $hash );
} else {
return "TelegramBot_Set: Command $cmd no token specified or addtl parameters given";
}
} elsif($cmd eq 'reset') {
Log3 $name, 5, "TelegramBot_Set $name: reset requested ";
TelegramBot_Setup( $hash );
} elsif($cmd eq 'replaceContacts') {
if ( $numberOfArgs < 2 ) {
return "TelegramBot_Set: Command $cmd, need to specify contacts string separate by space and contacts in the form of <id>:<full_name>:[@<username>|#<groupname>] ";
}
my $arg = join(" ", @args );
Log3 $name, 3, "TelegramBot_Set $name: set new contacts to :$arg: ";
# first set the hash accordingly
TelegramBot_CalcContactsHash($hash, $arg);
# then calculate correct string reading and put this into the reading
my @dumarr;
TelegramBot_ContactUpdate($hash, @dumarr);
Log3 $name, 5, "TelegramBot_Set $name: contacts newly set ";
}
if ( ! defined( $ret ) ) {
Log3 $name, 5, "TelegramBot_Set $name: $cmd done succesful: ";
} else {
Log3 $name, 5, "TelegramBot_Set $name: $cmd failed with :$ret: ";
}
return $ret
}
#####################################
# get function for gaining information from device
sub TelegramBot_Get($@)
{
my ( $hash, $name, @args ) = @_;
Log3 $name, 5, "TelegramBot_Get $name: called ";
### Check Args
my $numberOfArgs = int(@args);
return "TelegramBot_Get: No value specified for get" if ( $numberOfArgs < 1 );
my $cmd = $args[0];
my $arg = ($args[1] ? $args[1] : "");
if(!exists($gets{$cmd})) {
my @cList;
foreach my $k (sort keys %gets) {
my $opts = undef;
$opts = $sets{$k};
if (defined($opts)) {
push(@cList,$k . ':' . $opts);
} else {
push (@cList,$k);
}
} # end foreach
return "TelegramBot_Get: Unknown argument $cmd, choose one of " . join(" ", @cList);
} # error unknown cmd handling
Log3 $name, 4, "TelegramBot_Get $name: Processing TelegramBot_Get( $cmd )";
my $ret = undef;
if($cmd eq 'urlForFile') {
if ( $numberOfArgs != 2 ) {
return "TelegramBot_Get: Command $cmd, no file id specified";
}
$hash->{fileUrl} = "";
# return URL for file id
my $url = TelegramBot_getBaseURL($hash)."getFile?file_id=".urlEncode($arg);
my $guret = TelegramBot_DoUrlCommand( $hash, $url );
my $token = TelegramBot_readToken( $hash );
if ( ( defined($guret) ) && ( ref($guret) eq "HASH" ) ) {
if ( defined($guret->{file_path} ) ) {
# URL is https://api.telegram.org/file/bot<token>/<file_path>
my $filePath = $guret->{file_path};
$hash->{fileUrl} = "https://api.telegram.org/file/bot".$token."/".$filePath;
$ret = $hash->{fileUrl};
} else {
$ret = "urlForFile failed: no file path found";
$hash->{fileUrl} = $ret;
}
} else {
$ret = "urlForFile failed: ".(defined($guret)?$guret:"<undef>");
$hash->{fileUrl} = $ret;
}
} elsif ( $cmd eq "update" ) {
$ret = TelegramBot_UpdatePoll( $hash, "doOnce" );
} elsif ( $cmd eq "peerId" ) {
if ( $numberOfArgs != 2 ) {
return "TelegramBot_Get: Command $cmd, peer specified";
}
$ret = TelegramBot_GetIdForPeer( $hash, $arg );
}
Log3 $name, 5, "TelegramBot_Get $name: done with ".( defined($ret)?$ret:"<undef>").": ";
return $ret
}
##############################
# attr function for setting fhem attributes for the device
sub TelegramBot_Attr(@) {
my ($cmd,$name,$aName,$aVal) = @_;
my $hash = $defs{$name};
Log3 $name, 5, "TelegramBot_Attr $name: called ";
return "\"TelegramBot_Attr: \" $name does not exist" if (!defined($hash));
if (defined($aVal)) {
Log3 $name, 5, "TelegramBot_Attr $name: $cmd on $aName to $aVal";
} else {
Log3 $name, 5, "TelegramBot_Attr $name: $cmd on $aName to <undef>";
}
# $cmd can be "del" or "set"
# $name is device name
# aName and aVal are Attribute name and value
if ($aName eq 'favorites') {
# Empty current alias list in hash
if ( defined( $hash->{AliasCmds} ) ) {
foreach my $key (keys %{$hash->{AliasCmds}} )
{
delete $hash->{AliasCmds}{$key};
}
} else {
$hash->{AliasCmds} = {};
}
if ($cmd eq "set") {
# keep double ; for inside commands
$aVal =~ s/;;/SeMiCoLoN/g;
my @clist = split( /;/, $aVal);
my $newVal = "";
my $cnt = 0;
foreach my $cs ( @clist ) {
$cs =~ s/SeMiCoLoN/;;/g; # reestablish double ; for inside commands
my ( $alias, $desc, $minusdesc, $parsecmd, $needsConfirm, $needsResult, $hidden ) = TelegramBot_SplitFavoriteDef( $hash, $cs );
# Debug "parsecmd :".$parsecmd.": ".length($parsecmd);
next if ( ! $parsecmd ); # skip emtpy commands
next if ( length($parsecmd) == 0 ); # skip emtpy commands
$cnt += 1;
$newVal .= ";" if ( length($newVal)>0 );
$newVal .= $cs;
if ( $alias ) {
my $alx = $alias;
my $alcmd = $parsecmd;
Log3 $name, 2, "TelegramBot_Attr $name: Alias $alcmd defined multiple times" if ( defined( $hash->{AliasCmds}{$alx} ) );
$hash->{AliasCmds}{$alx} = $cnt;
}
}
# set attribute value to newly combined commands
$attr{$name}{'favorites'} = $newVal;
$aVal = $newVal;
}
} elsif ($aName eq 'allowedCommands') {
my $allowedName = "allowed_$name";
my $exists = ($defs{$allowedName} ? 1 : 0);
my $alcmd = (($cmd eq "set")?$aVal:"<none>");
AnalyzeCommand(undef, "defmod $allowedName allowed");
AnalyzeCommand(undef, "attr $allowedName validFor $name");
AnalyzeCommand(undef, "attr $allowedName $aName ".$alcmd);
Log3 $name, 3, "TelegramBot_Attr $name: ".($exists ? "modified":"created")." $allowedName with commands :$alcmd:";
# allowedCommands only set on the corresponding allowed_device
return "\"TelegramBot_Attr: \" $aName ".($exists ? "modified":"created")." $allowedName with commands :$alcmd:"