forked from viegener/Telegram-fhem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path50_TelegramBot.pm
2134 lines (1632 loc) · 72.6 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
#
# $Id: 50_TelegramBot.pm 9502 2015-10-17 20:36:21Z viegener $
#
##############################################################################
# 0.0 2015-09-16 Started
# 1.0 2015-10-17 Initial SVN-Version
#
# INTERNAL: sendIt allows providing a keyboard json
# Favorites sent as keyboard
# allow sending to contacts not in the contacts list (by giving id of user)
# added comment on save (statefile) for correct operation in documentation
# contacts changed on new contacts found
# saveStateOnContactChange attribute to disaloow statefile save on contact change
# writeStatefile on contact change
# make contact restore simpler --> whenever new contact found write all contacts into log with loglevel 1
# Do not allow shutdown as command for execution
# ret from command handlings logged
# maxReturnSize for command results
# limit sentMsgTxt internal to 1000 chars (even if longer texts are sent)
# contact reading now written in contactsupdate before statefile written
# documentation corrected - forum#msg350873
# cleanup on comments
# removed old version changes to history.txt
# add digest readings for error
# attribute to reduce logging on updatepoll errors - pollingVerbose:0_None,1_Digest,2_Log - (no log, default digest log daily, log every issue)
# documentation for pollingverbose
# reset / log polling status also in case of no error
# removed remark on timeout of 20sec
# LastCommands returns keyboard with commands
# added send / image command for compatibility with yowsup
# image not in cmd list to avoid this being first option
#
#
#
##############################################################################
# TASKS
#
# allow keyboards in the api
#
# dialog function
#
# allowed commands
#
#
##############################################################################
# Ideas / Future
# add replyTo
#
##############################################################################
package main;
use strict;
use warnings;
use HttpUtils;
use Encode;
use JSON;
use File::Basename;
use Scalar::Util qw(reftype looks_like_number);
#########################
# Forward declaration
sub TelegramBot_Define($$);
sub TelegramBot_Undef($$);
sub TelegramBot_Set($@);
sub TelegramBot_Get($@);
sub TelegramBot_Callback($$$);
#########################
# Globals
my %sets = (
"message" => "textField",
"msg" => "textField",
"send" => "textField",
"sendImage" => "textField",
# "image" => "textField",
"replaceContacts" => "textField",
"reset" => undef,
"zDebug" => "textField"
);
my %deprecatedsets = (
"messageTo" => "textField",
"sendImageTo" => "textField",
"sendPhoto" => "textField",
"sendPhotoTo" => "textField"
);
my %gets = (
# "msgById" => "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_hu_upd_params = (
url => "",
timeout => 5,
method => "GET",
header => $TelegramBot_header,
isPolling => "update",
hideurl => 1,
callback => \&TelegramBot_Callback
);
my %TelegramBot_hu_do_params = (
url => "",
timeout => 30,
method => "GET",
header => $TelegramBot_header,
hideurl => 1,
callback => \&TelegramBot_Callback
);
##############################################################################
##############################################################################
##
## 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) = @_;
require "$attr{global}{modpath}/FHEM/DevIo.pm";
$hash->{DefFn} = "TelegramBot_Define";
$hash->{UndefFn} = "TelegramBot_Undef";
$hash->{StateFn} = "TelegramBot_State";
$hash->{GetFn} = "TelegramBot_Get";
$hash->{SetFn} = "TelegramBot_Set";
$hash->{AttrFn} = "TelegramBot_Attr";
$hash->{AttrList} = "defaultPeer defaultPeerCopy:0,1 pollingTimeout cmdKeyword cmdSentCommands favorites:textField-long cmdFavorites cmdRestrictedPeer cmdTriggerOnly:0,1 saveStateOnContactChange:1,0 maxFileSize maxReturnSize pollingVerbose:1_Digest,2_Log,0_None ".
$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( int(@a) != 3 ) {
$errmsg = "syntax error: define <name> TelegramBot <APIid> ";
Log3 $name, 1, "TelegramBot $name: " . $errmsg;
return $errmsg;
}
if ( $a[2] =~ /^([[:alnum:]]|[-:_])+[[:alnum:]]+([[:alnum:]]|[-:_])+$/ ) {
$hash->{Token} = $a[2];
} else {
$errmsg = "specify valid API token containing only alphanumeric characters and -: characters: define <name> TelegramBot <APItoken> ";
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;
$hash->{HU_UPD_PARAMS} = \%TelegramBot_hu_upd_params;
$hash->{HU_DO_PARAMS} = \%TelegramBot_hu_do_params;
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(\%TelegramBot_hu_upd_params);
HttpUtils_Close(\%TelegramBot_hu_do_params);
RemoveInternalTimer($hash);
Log3 $name, 4, "TelegramBot_Undef $name: done ";
return 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, 4, "TelegramBot_Set $name: called ";
### Check Args
my $numberOfArgs = int(@args);
return "TelegramBot_Set: No value specified for set" if ( $numberOfArgs < 1 );
my $cmd = shift @args;
Log3 $name, 4, "TelegramBot_Set $name: Processing TelegramBot_Set( $cmd )";
if( (!exists($sets{$cmd})) && (!exists($deprecatedsets{$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
my $ret = undef;
if( ($cmd eq 'message') || ($cmd eq 'msg') || ($cmd eq 'send') ) {
if ( $numberOfArgs < 2 ) {
return "TelegramBot_Set: Command $cmd, no text (and no optional peer) specified";
}
my $peer;
if ( $args[0] =~ /^@(..+)$/ ) {
$peer = $1;
shift @args;
return "TelegramBot_Set: Command $cmd, no text specified" if ( $numberOfArgs < 3 );
} else {
$peer = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peer) );
}
# should return undef if succesful
Log3 $name, 4, "TelegramBot_Set $name: start message send ";
my $arg = join(" ", @args );
$ret = TelegramBot_SendIt( $hash, $peer, $arg, undef, 1 );
} elsif ( ($cmd eq 'sendPhoto') || ($cmd eq 'sendImage') || ($cmd eq 'image') ) {
if ( $numberOfArgs < 2 ) {
return "TelegramBot_Set: Command $cmd, need to specify filename ";
}
my $peer;
if ( $args[0] =~ /^@(..+)$/ ) {
$peer = $1;
shift @args;
return "TelegramBot_Set: Command $cmd, need to specify filename" if ( $numberOfArgs < 3 );
} else {
$peer = AttrVal($name,'defaultPeer',undef);
return "TelegramBot_Set: Command $cmd, without explicit peer requires defaultPeer being set" if ( ! defined($peer) );
}
# should return undef if succesful
my $file = shift @args;
$file = $1 if ( $file =~ /^\"(.*)\"$/ );
my $caption;
$caption = join(" ", @args ) if ( int(@args) > 0 );
Log3 $name, 5, "TelegramBot_Set $name: start photo send ";
# $ret = "TelegramBot_Set: Command $cmd, not yet supported ";
$ret = TelegramBot_SendIt( $hash, $peer, $file, $caption, 0 );
# DEPRECATED
} elsif($cmd eq 'messageTo') {
if ( $numberOfArgs < 3 ) {
return "TelegramBot_Set: Command $cmd, need to specify peer and text ";
}
# should return undef if succesful
my $peer = shift @args;
my $arg = join(" ", @args );
Log3 $name, 4, "TelegramBot_Set $name: start message send ";
$ret = TelegramBot_SendIt( $hash, $peer, $arg, undef, 1 );
# DEPRECATED
} elsif ( ($cmd eq 'sendPhotoTo') || ($cmd eq 'sendImageTo') ) {
if ( $numberOfArgs < 3 ) {
return "TelegramBot_Set: Command $cmd, need to specify peer and text ";
}
# should return undef if succesful
my $peer = shift @args;
my $file = shift @args;
$file = $1 if ( $file =~ /^\"(.*)\"$/ );
my $caption;
$caption = join(" ", @args ) if ( $numberOfArgs > 3 );
Log3 $name, 5, "TelegramBot_Set $name: start photo send to $peer";
$ret = TelegramBot_SendIt( $hash, $peer, $file, $caption, 0 );
} elsif($cmd eq 'zDebug') {
# for internal testing only
Log3 $name, 5, "TelegramBot_Set $name: start debug option ";
# delete $hash->{sentMsgPeer};
# BOTONLY
} 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] : "");
Log3 $name, 5, "TelegramBot_Get $name: Processing TelegramBot_Get( $cmd )";
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
my $ret = undef;
if($cmd eq 'msgById') {
if ( $numberOfArgs != 2 ) {
return "TelegramBot_Set: Command $cmd, no msg id specified";
}
Log3 $name, 5, "TelegramBot_Get $name: $cmd not supported yet";
# should return undef if succesful
$ret = TelegramBot_GetMessage( $hash, $arg );
}
Log3 $name, 5, "TelegramBot_Get $name: done with $ret: ";
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 ($cmd eq "set") {
if ($aName eq 'defaultPeer') {
$attr{$name}{'defaultPeer'} = $aVal;
} elsif ($aName eq 'cmdKeyword') {
$attr{$name}{'cmdKeyword'} = $aVal;
} elsif ($aName eq 'cmdSentCommands') {
$attr{$name}{'cmdSentCommands'} = $aVal;
} elsif ($aName eq 'cmdFavorites') {
$attr{$name}{'cmdFavorites'} = $aVal;
} elsif ($aName eq 'favorites') {
$attr{$name}{'favorites'} = $aVal;
} elsif ($aName eq 'cmdRestrictedPeer') {
$aVal =~ s/^\s+|\s+$//g;
$attr{$name}{'cmdRestrictedPeer'} = $aVal;
} elsif ($aName eq 'defaultPeerCopy') {
$attr{$name}{'defaultPeerCopy'} = ($aVal eq "1")? "1": "0";
} elsif ($aName eq 'saveStateOnContactChange') {
$attr{$name}{'saveStateOnContactChange'} = ($aVal eq "1")? "1": "0";
} elsif ($aName eq 'cmdTriggerOnly') {
$attr{$name}{'cmdTriggerOnly'} = ($aVal eq "1")? "1": "0";
} elsif ($aName eq 'maxFileSize') {
if ( $aVal =~ /^[[:digit:]]+$/ ) {
$attr{$name}{'maxFileSize'} = $aVal;
}
} elsif ($aName eq 'maxReturnSize') {
if ( $aVal =~ /^[[:digit:]]+$/ ) {
$attr{$name}{'maxReturnSize'} = $aVal;
}
} elsif ($aName eq 'pollingTimeout') {
if ( $aVal =~ /^[[:digit:]]+$/ ) {
$attr{$name}{'pollingTimeout'} = $aVal;
}
# let all existing methods run into block
RemoveInternalTimer($hash);
$hash->{POLLING} = -1;
# wait some time before next polling is starting
TelegramBot_ResetPolling( $hash );
}
}
return undef;
}
##############################################################################
##############################################################################
##
## Command handling
##
##############################################################################
##############################################################################
#####################################
#####################################
# INTERNAL: Check for cmdkeyword given
sub TelegramBot_checkCmdKeyword($$$$) {
my ($hash, $mpeernorm, $mtext, $attrName ) = @_;
my $name = $hash->{NAME};
my $cmd;
# command key word aus Attribut holen
my $ck = AttrVal($name,$attrName,undef);
# Log3 $name, 3, "TelegramBot_checkCmdKeyword $name: check :".$mtext.": against defined :".$ck.": results in ".index($mtext,$ck);
return $cmd if ( ! defined( $ck ) );
return $cmd if ( index($mtext,$ck) != 0 );
$cmd = substr( $mtext, length($ck) );
$cmd =~ s/^\s+|\s+$//g;
# get human readble name for peer
my $pname = TelegramBot_GetFullnameForContact( $hash, $mpeernorm );
# validate security criteria for commands and return cmd if succesful
return $cmd if ( TelegramBot_checkAllowedPeer( $hash, $mpeernorm ) );
# unauthorized fhem cmd
Log3 $name, 1, "TelegramBot_checkCmdKeyword($attrName) unauthorized cmd from user :$pname: ($mpeernorm) \n Cmd: $cmd";
my $ret = "UNAUTHORIZED: TelegramBot fhem request for $attrName from user :$pname: ($mpeernorm) \n Cmd: $cmd";
# send unauthorized to defaultpeer
my $defpeer = AttrVal($name,'defaultPeer',undef);
$defpeer = TelegramBot_GetIdForPeer( $hash, $defpeer ) if ( defined( $defpeer ) );
if ( defined( $defpeer ) ) {
AnalyzeCommand( undef, "set $name message $ret", "" );
}
return undef;
}
#####################################
#####################################
# INTERNAL: handle sentlast and favorites
sub TelegramBot_SentFavorites($$$$) {
my ($hash, $mpeernorm, $mtext, $mid ) = @_;
my $name = $hash->{NAME};
my $ret;
my $cmd = TelegramBot_checkCmdKeyword( $hash, $mpeernorm, $mtext, 'cmdFavorites' );
return $ret if ( ! defined( $cmd ) );
Log3 $name, 4, "TelegramBot_SentFavorites cmd correct peer ";
my $slc = AttrVal($name,'favorites',"");
Log3 $name, 4, "TelegramBot_SentFavorites Favorites :$slc: ";
my @clist = split( /;/, $slc);
$cmd = $1 if ( $cmd =~ /^\s*([0-9]+)[^0-9=]*=.*$/ );
# if given a number execute the numbered favorite as a command
if ( looks_like_number( $cmd ) ) {
return $ret if ( $cmd == 0 );
my $cmdId = ($cmd-1);
# Log3 $name, 3, "TelegramBot_SentFavorites exec cmd :$cmdId: ";
if ( ( $cmdId >= 0 ) && ( $cmdId < scalar( @clist ) ) ) {
$cmd = $clist[$cmdId];
$ret = TelegramBot_ExecuteCommand( $hash, $mpeernorm, $cmd );
} else {
Log3 $name, 3, "TelegramBot_SentFavorites cmd id not defined :($cmdId+1): ";
}
}
# ret not defined means no favorite found that matches cmd or no fav given in cmd
if ( ! defined( $ret ) ) {
my $cnt = 0;
my @keys = ();
my $fcmd = AttrVal($name,'cmdFavorites',undef);
foreach my $cs ( @clist ) {
$cnt += 1;
my @tmparr = ( $fcmd.$cnt." = ".$cs );
push( @keys, \@tmparr );
}
my @tmparr = ( $fcmd."0 = Abbruch" );
push( @keys, \@tmparr );
my $jsonkb = TelegramBot_MakeKeyboard( $hash, 1, @keys );
Log3 $name, 5, "TelegramBot_SentFavorites keyboard:".$jsonkb.": ";
$ret = "TelegramBot fhem : ($mpeernorm)\n Favorites \n";
$ret = TelegramBot_SendIt( $hash, $mpeernorm, $ret, $jsonkb, 1 );
############ OLD Favorites sent as message
# Log3 $name, 3, "TelegramBot_SentFavorites Favorites :".scalar(@clist).": ";
# my $cnt = 0;
# $slc = "";
# my $ck = AttrVal($name,'cmdKeyword',"");
# foreach my $cs ( @clist ) {
# $cnt += 1;
# $slc .= $cnt."\n $ck ".$cs."\n";
# }
# my $defpeer = AttrVal($name,'defaultPeer',undef);
# $defpeer = TelegramBot_GetIdForPeer( $hash, $defpeer ) if ( defined( $defpeer ) );
# $ret = "TelegramBot fhem : ($mpeernorm)\n Favorites \n\n".$slc;
# $ret = TelegramBot_SendIt( $hash, $defpeer, $ret, $mid, 1 );
}
return $ret;
}
#####################################
#####################################
# INTERNAL: handle sentlast and favorites
sub TelegramBot_SentLastCommand($$$) {
my ($hash, $mpeernorm, $mtext ) = @_;
my $name = $hash->{NAME};
my $ret;
my $cmd = TelegramBot_checkCmdKeyword( $hash, $mpeernorm, $mtext, 'cmdSentCommands' );
return $ret if ( ! defined( $cmd ) );
Log3 $name, 5, "TelegramBot_SentLastCommand cmd correct peer ";
my $slc = ReadingsVal($name ,"StoredCommands","");
my $defpeer = AttrVal($name,'defaultPeer',undef);
$defpeer = TelegramBot_GetIdForPeer( $hash, $defpeer ) if ( defined( $defpeer ) );
my @cmds = split( "\n", $slc );
# create keyboard
my @keys = ();
foreach my $cs ( @cmds ) {
my @tmparr = ( $cs );
push( @keys, \@tmparr );
}
# my @tmparr = ( $fcmd."0 = Abbruch" );
# push( @keys, \@tmparr );
my $jsonkb = TelegramBot_MakeKeyboard( $hash, 1, @keys );
$ret = "TelegramBot fhem : $mpeernorm \n Last Commands \n";
# overwrite ret with result from SendIt --> send response
$ret = TelegramBot_SendIt( $hash, $mpeernorm, $ret, $jsonkb, 1 );
############ OLD SentLastCommands sent as message
# $ret = "TelegramBot fhem : $mpeernorm \nLast Commands \n\n".$slc;
# # overwrite ret with result from Analyzecommand --> send response
# $ret = AnalyzeCommand( undef, "set $name message \@$mpeernorm $ret", "" );
return $ret;
}
#####################################
#####################################
# INTERNAL: execute command and sent return value
sub TelegramBot_ReadHandleCommand($$$) {
my ($hash, $mpeernorm, $mtext ) = @_;
my $name = $hash->{NAME};
my $ret;
my $cmd = TelegramBot_checkCmdKeyword( $hash, $mpeernorm, $mtext, 'cmdKeyword' );
return $ret if ( ! defined( $cmd ) );
Log3 $name, 3, "TelegramBot_ReadHandleCommand $name: cmd found :".$cmd.": ";
# get human readble name for peer
my $pname = TelegramBot_GetFullnameForContact( $hash, $mpeernorm );
Log3 $name, 5, "TelegramBot_ReadHandleCommand cmd correct peer ";
# Either no peer defined or cmdpeer matches peer for message -> good to execute
my $cto = AttrVal($name,'cmdTriggerOnly',"0");
if ( $cto eq '1' ) {
$cmd = "trigger ".$cmd;
}
Log3 $name, 5, "TelegramBot_ReadHandleCommand final cmd for analyze :".$cmd.": ";
# store last commands (original text)
TelegramBot_AddStoredCommands( $hash, $mtext );
$ret = TelegramBot_ExecuteCommand( $hash, $mpeernorm, $cmd );
return $ret;
}
#####################################
#####################################
# INTERNAL: execute command and sent return value
sub TelegramBot_ExecuteCommand($$$) {
my ($hash, $mpeernorm, $cmd ) = @_;
my $name = $hash->{NAME};
my $ret;
# get human readble name for peer
my $pname = TelegramBot_GetFullnameForContact( $hash, $mpeernorm );
Log3 $name, 5, "TelegramBot_ExecuteCommand final cmd for analyze :".$cmd.": ";
# special case shutdown caught here to avoid endless loop
$ret = "shutdown command can not be executed" if ( $cmd =~ /^shutdown(\s+.*)?$/ );
# Execute command
$ret = AnalyzeCommand( undef, $cmd, "" ) if ( ! defined( $ret ) );
Log3 $name, 5, "TelegramBot_ExecuteCommand result for analyze :".(defined($ret)?$ret:"<undef>").": ";
my $defpeer = AttrVal($name,'defaultPeer',undef);
$defpeer = TelegramBot_GetIdForPeer( $hash, $defpeer ) if ( defined( $defpeer ) );
my $retstart = "TelegramBot fhem";
$retstart .= " from $pname ($mpeernorm)" if ( $defpeer ne $mpeernorm );
# undef is considered ok
if ( ( ! defined( $ret ) ) || ( length( $ret) == 0 ) ) {
$ret = "$retstart cmd :$cmd: result OK";
} else {
$ret = "$retstart cmd :$cmd: result :$ret:";
}
Log3 $name, 5, "TelegramBot_ExecuteCommand $name: ".$ret.": ";
# replace line ends with spaces
# $ret =~ s/(\r|\n)/ /gm;
$ret =~ s/\r//gm;
# shorten to maxReturnSize if set
my $limit = AttrVal($name,'maxReturnSize',0);
if ( ( length($ret) > $limit ) && ( $limit != 0 ) ) {
$ret = substr( $ret, 0, $limit )."\n\n...";
}
$ret = AnalyzeCommand( undef, "set $name message \@$mpeernorm $ret", "" );
my $dpc = AttrVal($name,'defaultPeerCopy',1);
if ( ( $dpc ) && ( defined( $defpeer ) ) ) {
if ( $defpeer ne $mpeernorm ) {
AnalyzeCommand( undef, "set $name message $ret", "" );
}
}
return $ret;
}
######################################
# add a command to the StoredCommands reading
# hash, cmd
sub TelegramBot_AddStoredCommands($$) {
my ($hash, $cmd) = @_;
my $stcmds = ReadingsVal($hash->{NAME},"StoredCommands","");
$stcmds = $stcmds;
if ( $stcmds !~ /^\Q$cmd\E$/m ) {
# add new cmd
$stcmds .= $cmd."\n";
# check number lines
my $num = ( $stcmds =~ tr/\n// );
if ( $num > 10 ) {
$stcmds =~ /^[^\n]+\n(.*)$/s;
$stcmds = $1;
}
# change reading
readingsSingleUpdate($hash, "StoredCommands", $stcmds , 1);
Log3 $hash->{NAME}, 4, "TelegramBot_AddStoredCommands :$stcmds: ";
}
}
##############################################################################
##############################################################################
##
## Communication - Send - receive - Parse
##
##############################################################################
##############################################################################
#####################################
# INTERNAL: Function to send a photo (and text message) to a peer and handle result
# addPar is caption for images / keyboard for text
sub TelegramBot_SendIt($$$$$)
{
my ( $hash, @args) = @_;
my ( $peer, $msg, $addPar, $isText) = @args;
my $name = $hash->{NAME};
Log3 $name, 5, "TelegramBot_SendIt $name: called ";
if ( ( defined( $hash->{sentMsgResult} ) ) && ( $hash->{sentMsgResult} eq "WAITING" ) ){
# add to queue
if ( ! defined( $hash->{sentQueue} ) ) {
$hash->{sentQueue} = [];
}
Log3 $name, 3, "TelegramBot_SendIt $name: add send to queue :$peer: -:$msg: - :".(defined($addPar)?$addPar:"<undef>").":";
push( @{ $hash->{sentQueue} }, \@args );
return;
}
my $ret;
$hash->{sentMsgResult} = "WAITING";
# trim and convert spaces in peer to underline
my $peer2 = TelegramBot_GetIdForPeer( $hash, $peer );
if ( ! defined( $peer2 ) ) {
$ret = "FAILED peer not found :$peer:";
# Log3 $name, 2, "TelegramBot_SendIt $name: failed with :".$ret.":";
$peer2 = "";
}
$hash->{sentMsgPeer} = TelegramBot_GetFullnameForContact( $hash, $peer2 );
$hash->{sentMsgPeerId} = $peer2;
# init param hash
$TelegramBot_hu_do_params{hash} = $hash;
$TelegramBot_hu_do_params{header} = $TelegramBot_header;
delete( $TelegramBot_hu_do_params{boundary} );
# handle data creation only if no error so far
if ( ! defined( $ret ) ) {
# add chat / user id (no file) --> this will also do init
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, "chat_id", undef, $peer2, 0 );
if ( $isText ) {
$TelegramBot_hu_do_params{url} = $hash->{URL}."sendMessage";
# $TelegramBot_hu_do_params{url} = "http://requestb.in/1dvvb8u1";
if ( length($msg) > 1000 ) {
$hash->{sentMsgText} = substr($msg,0, 1000)."...";
} else {
$hash->{sentMsgText} = $msg;
}
# my $c = chr(10);
# $msg =~ s/([^\\])\\n/$1$c/g;
# add msg (no file)
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, "text", undef, $msg, 0 ) if ( ! defined( $ret ) );
if ( defined( $addPar ) ) {
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, "reply_markup", undef, $addPar, 0 ) if ( ! defined( $ret ) );
}
} else {
# Photo send
$hash->{sentMsgText} = "Image: $msg".(( defined( $addPar ) )?" - ".$addPar:"");
$TelegramBot_hu_do_params{url} = $hash->{URL}."sendPhoto";
# $TelegramBot_hu_do_params{url} = "http://requestb.in/q6o06yq6";
# add caption
if ( defined( $addPar ) ) {
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, "caption", undef, $addPar, 0 ) if ( ! defined( $ret ) );
}
# add msg (no file)
Log3 $name, 4, "TelegramBot_SendIt $name: Filename for image file :$msg:";
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, "photo", undef, $msg, 1 ) if ( ! defined( $ret ) );
# only for test / debug
$TelegramBot_hu_do_params{loglevel} = 3;
}
# finalize multipart
$ret = TelegramBot_AddMultipart($hash, \%TelegramBot_hu_do_params, undef, undef, undef, 0 ) if ( ! defined( $ret ) );
}
if ( defined( $ret ) ) {
Log3 $name, 3, "TelegramBot_SendIt $name: Failed with :$ret:";
TelegramBot_Callback( \%TelegramBot_hu_do_params, $ret, "");
} else {
HttpUtils_NonblockingGet( \%TelegramBot_hu_do_params);
}
return $ret;
}
#####################################
# INTERNAL: Build a multipart form data in a given hash
# Parameter
# hash (device hash)
# params (hash for building up the data)
# paramname --> if not sepecifed / undef - multipart will be finished
# header for multipart
# content
# isFile to specify if content is providing a file to be read as content
# > returns string in case of error or undef
sub TelegramBot_AddMultipart($$$$$$)
{
my ( $hash, $params, $parname, $parheader, $parcontent, $isFile ) = @_;
my $name = $hash->{NAME};
my $ret;
# Check if boundary is defined
if ( ! defined( $params->{boundary} ) ) {
$params->{boundary} = "TelegramBot_boundary-x0123";
$params->{header} .= "\r\nContent-Type: multipart/form-data; boundary=".$params->{boundary};
$params->{method} = "POST";
$params->{data} = "";
}
# ensure parheader is defined and add final header new lines
$parheader = "" if ( ! defined( $parheader ) );
$parheader .= "\r\n" if ( ( length($parheader) > 0 ) && ( $parheader !~ /\r\n$/ ) );
# add content
my $finalcontent;
if ( defined( $parname ) ) {
$params->{data} .= "--".$params->{boundary}."\r\n";
if ( $isFile ) {
my $baseFilename = basename($parcontent);
$parheader = "Content-Disposition: form-data; name=\"".$parname."\"; filename=\"".$baseFilename."\"\r\n".$parheader."\r\n";
return( "FAILED file :$parcontent: not found or empty" ) if ( ! -e $parcontent ) ;