forked from nonlin-lin-chaos-order-etc-etal/GREENBICH
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
1643 lines (1466 loc) · 82.7 KB
/
main.py
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
from random import choice
import traceback as tb
import traceback
import socket
import pytz
# import socks
import sys
import time
import requests
import settings
import translate_krzb
import whois
import json
from urllib.parse import unquote
from urllib.parse import quote as urlencode
from settings import settings as option
from threading import Thread
import traceback
import datetime
LOG_TRACE = True
ENABLE_EXMO = False
def settings_by_key(key):
return config[key]
def getconfig():
return config
def get_create_ctx_from_mask2ctx(mask2ctx, mask):
if mask in mask2ctx:
ctx = mask2ctx[mask]
else:
ctx = {}
mask2ctx[mask] = ctx
return ctx
def replace_nick_mask2ctx(mask2ctx, prev_mask, new_mask):
print(__name__, "replace_nick_mask2ctx(, prev_mask='"+str(prev_mask)+"', new_mask="+str(new_mask)+")", flush=True)
if prev_mask in mask2ctx:
ctx = mask2ctx[prev_mask]
del mask2ctx[prev_mask]
else:
ctx = {}
mask2ctx[new_mask]=ctx
def set_prev_msg(mask2ctx, mask, message):
print(__name__, f"set_prev_msg enter, args: (, mask='{mask}', message='{message}')", flush=True)
if mask is None or message is None:
print(__name__, "set_prev_msg point 1, leaving", flush=True)
return
#print(__name__, "set_prev_msg point 2", flush=True)
ctx = get_create_ctx_from_mask2ctx(mask2ctx, mask)
#print(__name__, "set_prev_msg point 3", flush=True)
ctx["prev_msg"]=message
print(__name__, "set_prev_msg point 4, leaving", flush=True)
def get_prev_msg(mask2ctx, mask):
ctx = get_create_ctx_from_mask2ctx(mask2ctx, mask)
return ctx["prev_msg"] if "prev_msg" in ctx else None
def fmt2(your_numeric_value):
return "{:0,.2f}".format(float(your_numeric_value))
from pytrends.request import TrendReq
while True:
try:
pytrends = TrendReq(hl='ru-RU', tz=360)
break
except KeyboardInterrupt as e:
raise e
except:
traceback.print_exc()
TIME_TO_SLEEP_SECONDS = 1
print ( "sleeping %s seconds" % str(TIME_TO_SLEEP_SECONDS) )
time.sleep(TIME_TO_SLEEP_SECONDS)
continue
def get_interest_by_country(country):
return pytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True, inc_geo_code=False)
def get_trending_searches(country_str, kwlist=None):
return pytrends.trending_searches(pn=country_str).to_numpy()
def convert_hex_to_ip(hex_value):
a=int(hex_value[0:2], 16)
b=int(hex_value[2:4], 16)
c=int(hex_value[4:6], 16)
d=int(hex_value[6:8], 16)
return "%s.%s.%s.%s" % (str(a), str(b), str(c), str(d))
# Function of parcing of get TITLE from link.
def link_title(n):
if 'http://' in n or 'https://' in n:
try:
link_r = n.split('//',1)[1].split(' ',1)[0].rstrip()
except:
print('Link wrong!')
elif 'www.' in n:
try:
link_r = n.split('www.',1)[1].split(' ',1)[0].rstrip()
except:
print('Link wrong!')
link = 'http://'+link_r
max_t_link = 30
t_link = time.time()
for i in requests.get(link, stream=True, verify=False):
t2_link = time.time()
if t2_link > t_link + max_t_link:
requests.get(link, stream=True).close()
print('Title - Ошибка! Превышено время ожидания!')
link_stat = False
break
else:
link_stat = True
if link_stat == True:
unquoted_link = unquote(link)
get_title = requests.get(link, timeout = 10)
txt_title = get_title.text
if '</TITLE>' in txt_title or '</title>' in txt_title\
or '</Title>' in txt_title:
if '</TITLE>' in txt_title:
title = '\x02Title\x02 of '+n+': '+\
txt_title.split('</TITLE>',1)[0].split('>')[-1]
elif '</title>' in txt_title:
title = '\x02Title\x02 of '+n+': '+\
txt_title.split('</title>',1)[0].split('>')[-1]
elif '</Title>' in txt_title:
title = '\x02Title\x02 of '+n+': '+\
txt_title.split('</Title>',1)[0].split('>')[-1]
return title.replace('\r','').replace('\n','').replace\
('www.','').replace('http://','').replace\
('https://','').strip()
else:
return 'Title not found'
def ru_latest_news_newsapi_org():
apikey=option("newsapi_apikey")
url="http://newsapi.org/v2/top-headlines?country=ru&apiKey=%s" % apikey
resp = requests.get(url=url)
if resp.status_code != 200: return []
#print (__file__, resp.text)
rjson = resp.json()
print(__file__, "ns_resp",json.dumps(rjson, sort_keys=True, indent=4))
if "articles" in rjson:
arts = rjson["articles"]
if arts is None: return []
return arts
return []
def ua_latest_news_newsapi_org():
apikey=option("newsapi_apikey")
url="http://newsapi.org/v2/top-headlines?country=ua&apiKey=%s" % apikey
resp = requests.get(url=url)
if resp.status_code != 200: return []
#print (__file__, resp.text)
rjson = resp.json()
print(__file__, "ns_resp",json.dumps(rjson, sort_keys=True, indent=4))
if "articles" in rjson:
arts = rjson["articles"]
if arts is None: return []
return arts
return []
def latest_news_google_news_ru():
apikey=option("newsapi_apikey")
url="http://newsapi.org/v2/top-headlines?sources=google-news-ru&apiKey=%s" % apikey
resp = requests.get(url=url)
if resp.status_code != 200: return []
# print (__file__, resp.text)
rjson = resp.json()
print(__file__, "ns_resp",json.dumps(rjson, sort_keys=True, indent=4))
if "articles" in rjson:
arts = rjson["articles"]
if arts is None: return []
return arts
return []
def format_currency(value):
return "{:0,.2f}".format(float(value))
def format_total_cap(total_market_cap_usd):
total_market_cap_usd_t = float(total_market_cap_usd) / 1.0e12
b = "{:0,.2f}".format(total_market_cap_usd_t)+"T USD"
p = "{:0,.2f}".format(total_market_cap_usd_t/60.0*100.0)+'% of entire world cap e.g. 60T USD'
return b+" ("+p+')'
def fetch_last_hour_new_news(old_news_cache=None, kwlist=None):
array = get_trending_searches(country_str="russia", kwlist=kwlist)
newer = []
for lines in array:
line = lines[0]
if line is None: continue
if line in old_news_cache: continue
newer.append(line)
return newer
def is_runews_command(bot_nick, str_line):
#:[email protected] PRIVMSG BichBot :Чтобы получить войс, ответьте на вопрос: Как называется blah blah?
dataTokensDelimitedByWhitespace = str_line.split(" ")
#dataTokensDelimitedByWhitespace[0] :[email protected]
#dataTokensDelimitedByWhitespace[1] PRIVMSG
#dataTokensDelimitedByWhitespace[2] #ru
# OR
#dataTokensDelimitedByWhitespace[2] BichBot
#dataTokensDelimitedByWhitespace[3] :!курс
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
where_mes_exc = communicationsLineName
if len(dataTokensDelimitedByWhitespace) > 3:
line = " ".join(dataTokensDelimitedByWhitespace[3:])
is_in_private_query = where_mes_exc == bot_nick
bot_mentioned = bot_nick in line
commWithBot = is_in_private_query or bot_mentioned
return commWithBot and ("runews" in line or "руновости" in line) or ("!runews" in line or "!руновости" in line)
else:
return False
def is_uanews_command(bot_nick, str_line):
#:[email protected] PRIVMSG BichBot :Чтобы получить войс, ответьте на вопрос: Как называется blah blah?
dataTokensDelimitedByWhitespace = str_line.split(" ")
#dataTokensDelimitedByWhitespace[0] :[email protected]
#dataTokensDelimitedByWhitespace[1] PRIVMSG
#dataTokensDelimitedByWhitespace[2] #ru
# OR
#dataTokensDelimitedByWhitespace[2] BichBot
#dataTokensDelimitedByWhitespace[3] :!курс
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
where_mes_exc = communicationsLineName
if len(dataTokensDelimitedByWhitespace) > 3:
line = " ".join(dataTokensDelimitedByWhitespace[3:])
is_in_private_query = where_mes_exc == bot_nick
bot_mentioned = bot_nick in line
commWithBot = is_in_private_query or bot_mentioned
return commWithBot and ("uanews" in line or "укрновости" in line) or ("!uanews" in line or "!укрновости" in line)
else:
return False
def is_search_command(bot_nick, str_line):
#:[email protected] PRIVMSG BichBot :Чтобы получить войс, ответьте на вопрос: Как называется blah blah?
dataTokensDelimitedByWhitespace = str_line.split(" ")
#dataTokensDelimitedByWhitespace[0] :[email protected]
#dataTokensDelimitedByWhitespace[1] PRIVMSG
#dataTokensDelimitedByWhitespace[2] #ru
# OR
#dataTokensDelimitedByWhitespace[2] BichBot
#dataTokensDelimitedByWhitespace[3] :!курс
#:server.org 332 GreenBich #ru :поисковик: search.org
if len(dataTokensDelimitedByWhitespace) < 4: return False
if dataTokensDelimitedByWhitespace[1] != "PRIVMSG": return False
communicationsLineName = dataTokensDelimitedByWhitespace[2]
where_mes_exc = communicationsLineName
line = " ".join(dataTokensDelimitedByWhitespace[3:])
is_in_private_query = where_mes_exc == bot_nick
bot_mentioned = bot_nick in line
commWithBot = is_in_private_query or bot_mentioned
return commWithBot and ("search" in line or "поиск" in line) or ("!search" in line or "!поиск" in line)
def is_search_command2(bot_nick, str_line):
#:[email protected] PRIVMSG BichBot :Чтобы получить войс, ответьте на вопрос: Как называется blah blah?
dataTokensDelimitedByWhitespace = data.split(" ")
#dataTokensDelimitedByWhitespace[0] :[email protected]
#dataTokensDelimitedByWhitespace[1] PRIVMSG
#dataTokensDelimitedByWhitespace[2] #ru
# OR
#dataTokensDelimitedByWhitespace[2] BichBot
#dataTokensDelimitedByWhitespace[3] :!курс
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
where_mes_exc = communicationsLineName
if len(dataTokensDelimitedByWhitespace) > 3:
line = " ".join(dataTokensDelimitedByWhitespace[3:])
is_in_private_query = where_mes_exc == bot_nick
bot_mentioned = bot_nick in line
commWithBot = is_in_private_query or bot_mentioned
return commWithBot and ("search2" in line or "поиск2" in line) or ("!search2" in line or "!поиск2" in line)
else:
return False
class MyPingsToServerThread(Thread):
def __init__(self, myBot):
Thread.__init__(self)
self.myBot = myBot
def run(self):
self.myBot.pinger_of_server()
def print_wheel(wheel):
s = "{[\r\n"
for dt in wheel['datetimes']:
s+=" "+str(dt)+"\r\n"
s+="]}"
return s
WHEEL_SIZE = 5
WHEEL_TIME_SECONDS = 60
class MyBot:
wheelGrants = {}
def grantCommand(self, sentBy, commLine):
sentBy = 'anyone' # nicks don't matter as ddoser might use multiple random nicks
if not sentBy in self.wheelGrants:
wheel = {}
self.wheelGrants[sentBy] = wheel
wheel['datetimes'] = [datetime.datetime.now(pytz.utc)]
print(__name__, f"command_granted clause 1, wheel: {print_wheel(wheel)}")
return True
else:
wheel = self.wheelGrants[sentBy]
datetimes = wheel['datetimes']
while len(datetimes) > WHEEL_SIZE:
datetimes = datetimes[1:]
wheel['datetimes'] = datetimes
if len(datetimes) < WHEEL_SIZE:
print(__name__, f"command_granted clause 3, wheel: {print_wheel(wheel)}")
datetimes.append(datetime.datetime.now(pytz.utc))
wheel['datetimes'] = datetimes
return True
granted = datetimes[0] < datetime.datetime.now(pytz.utc) - datetime.timedelta(seconds=WHEEL_TIME_SECONDS)
if not granted:
print(__name__, f"command not granted, wheel: {print_wheel(wheel)}")
if "floodDetectedSentTime" in wheel:
floodDetectedSentTime = wheel["floodDetectedSentTime"]
else:
floodDetectedSentTime = datetime.datetime.now(pytz.utc) - datetime.timedelta(days=1)
if floodDetectedSentTime < datetime.datetime.now(pytz.utc) - datetime.timedelta(seconds=WHEEL_TIME_SECONDS):
wheel["floodDetectedSentTime"] = datetime.datetime.now(pytz.utc)
self.send(f'PRIVMSG {commLine} :Flood detected, ignoring.\r\n')
else:
print(__name__, f"command_granted clause 2, wheel: {print_wheel(wheel)}")
datetimes.append(datetime.datetime.now(pytz.utc))
datetimes = datetimes[1:]
wheel['datetimes'] = datetimes
return granted
def connection_settings(self, key2):
return self.connection_settings_dict()[key2]
def connection_option(self, key2):
return self.connection_settings(key2)
def connection_setting_or_None(self, key2):
dic = self.connection_settings_dict()
return dic[key2] if key2 in dic else None
def connection_settings_dict(self):
return self.connection_props
def __init__(self, settings_key, connection_props):
self.settings_key = settings_key
self.connection_props = connection_props
self.irc_server_hostname = self.connection_settings('irc_server_hostname')
self.port = int(self.connection_settings('port'))
self.channelsProps = self.connection_settings('channelsProps')
self.channelsList = list(self.channelsProps.keys())
self.BOT_NAME_PREFIX = self.connection_settings('InitialBotNick')
self.botName = self.BOT_NAME_PREFIX
self.botNickSalt = 0
self.nickserv_password = self.connection_setting_or_None('nickserv_password')
self.coinmarketcap_apikey = settings.settings('coinmarketcap_apikey')
self.rapidapi_appkey = settings.settings('rapidapi_appkey')
self.titleEnabled = bool(self.connection_settings('titleEnabled'))
self.onlycmc = bool(self.connection_settings('onlycmc'))
self.enableother1 = not self.onlycmc
self.gnome1rur = float(settings.settings('gnome1_rur_float'))
self.gnomeBtcTransaction1 = float(settings.settings('gnome_btc_transaction1_BTC_float')) #BTC
self.gnome_btc_amount2_BTC_float = float(settings.settings('gnome_btc_amount2_BTC_float')) #BTC
self.master_secret = settings.settings('master_secret')
self.gnome1rur = self.gnome1rur + ((self.gnome_btc_amount2_BTC_float - self.gnomeBtcTransaction1) * 9500.0 * 65.0)
self.measurementRur1 = self.gnome1rur
self.measurementRur2 = self.gnome1rur
old_news_cache={}
old_news_cache_index={}
def web_search(self, query_str, number_of_results):
pageNumber=1
url="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI?q=%s&pageNumber=%s&pageSize=%s&autocorrect=true&safeSearch=true" % \
(urlencode(query_str),str(pageNumber),str(number_of_results))
headers = {'User-agent': 'bichbot/0.0.1',"X-RapidAPI-Host":"contextualwebsearch-websearch-v1.p.rapidapi.com","X-RapidAPI-Key":self.rapidapi_appkey}
resp = requests.get(url=url, headers=headers)
rjson = resp.json()
print("ws_resp",json.dumps(rjson, sort_keys=True, indent=4))
for v in rjson["value"]: return v["url"]
return None
def web_search2(self, query_str, number_of_results):
search2RestClient=Search2RestClient(option("dataforseo_api_login"), option("dataforseo_api_password"))
resp_json = search2RestClient.get(path)
pageNumber=1
url="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI?q=%s&pageNumber=%s&pageSize=%s&autocorrect=true&safeSearch=true" % \
(urlencode(query_str),str(pageNumber),str(number_of_results))
headers = {'User-agent': 'bichbot/0.0.1',"X-RapidAPI-Host":"contextualwebsearch-websearch-v1.p.rapidapi.com","X-RapidAPI-Key":self.rapidapi_appkey}
resp = requests.get(url=url, headers=headers)
rjson = resp.json()
print("ws_resp",json.dumps(rjson, sort_keys=True, indent=4))
for v in rjson["value"]: return v["url"]
return None
def news_search_ctxwebsrch(self, query_str, number_of_results):
pageNumber=1
url="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?q=%s&pageNumber=%s&pageSize=%s&autocorrect=true&safeSearch=true" % \
(urlencode(query_str),str(pageNumber),str(number_of_results))
headers = {'User-agent': 'bichbot/0.0.1',"X-RapidAPI-Host":"contextualwebsearch-websearch-v1.p.rapidapi.com","X-RapidAPI-Key":self.rapidapi_appkey}
resp = requests.get(url=url, headers=headers)
rjson = resp.json()
print("ns_resp",json.dumps(rjson, sort_keys=True, indent=4))
for v in rjson["value"]: return v["url"]
return None
def sendmsg(self, to_addr,msg):
self.send('PRIVMSG %s :%s\r\n'%(to_addr,msg))
def print_new_news_googletrends(self, to_addr, kwlist=None):
old_news_cache = self.old_news_cache
if to_addr in old_news_cache:
cache = old_news_cache[to_addr]
else:
cache={}
old_news_cache[to_addr]=cache
array_of_strings = fetch_last_hour_new_news(cache,kwlist=kwlist)
cnt = get_news_count_for_channel(to_addr)
sent = 0
index = 0
for line in array_of_strings:
if line is None: continue
resultUrl = news_search(line,1)
self.sendmsg(to_addr, "%s: %s %s" % (str((index+1)),line,resultUrl if resultUrl else ""))
cache[line] = {"recently_sent":True}
sent=sent+1
index=index+1
if sent >= cnt: break
if sent == 0: self.sendmsg(to_addr, "Нет новостей у меня")
def print_new_runews_newsapi_org(self, to_addr):
old_news_cache = self.old_news_cache
old_news_cache_index = self.old_news_cache_index
if to_addr in old_news_cache:
cache = old_news_cache[to_addr]
else:
cache={}
old_news_cache[to_addr]=cache
if to_addr in old_news_cache_index:
cache_index = old_news_cache_index[to_addr]
else:
cache_index=[]
old_news_cache_index[to_addr]=cache_index
arts = ru_latest_news_newsapi_org() + latest_news_google_news_ru()
cnt = self.get_news_count_for_channel(to_addr)
sent = 0
index = 0
for a in arts:
if a is None: continue
url = a["url"]
if url in cache: continue
self.sendmsg(to_addr, "%s %s" % ( str(url), str(a["title"]) ))
cache[url] = True
cache_index.append(url)
while len(cache_index)>100:
first_url = cache_index.pop(0)
del cache[first_url]
sent=sent+1
index=index+1
if sent >= cnt: break
if sent == 0: self.sendmsg(to_addr, "Нет новостей у меня")
def print_new_uanews_newsapi_org(self, to_addr):
old_news_cache = self.old_news_cache
old_news_cache_index = self.old_news_cache_index
if to_addr in old_news_cache:
cache = old_news_cache[to_addr]
else:
cache={}
old_news_cache[to_addr]=cache
if to_addr in old_news_cache_index:
cache_index = old_news_cache_index[to_addr]
else:
cache_index=[]
old_news_cache_index[to_addr]=cache_index
arts = ua_latest_news_newsapi_org()
cnt = self.get_news_count_for_channel(to_addr)
sent = 0
index = 0
for a in arts:
if a is None: continue
url = a["url"]
if url in cache: continue
self.sendmsg(to_addr, "%s %s" % ( str(url), str(a["title"]) ))
cache[url] = True
cache_index.append(url)
while len(cache_index)>100:
first_url = cache_index.pop(0)
del cache[first_url]
sent=sent+1
index=index+1
if sent >= cnt: break
if sent == 0: self.sendmsg(to_addr, "Нет новостей у меня")
def maybe_print_news(self, bot_nick, str_incoming_line):
dataTokensDelimitedByWhitespace = str_incoming_line.split(" ")
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
if is_runews_command(bot_nick, str_incoming_line):
if self.grantCommand(sentBy, communicationsLineName):
kwlist = []
where_mes_exc = communicationsLineName
line = " ".join(dataTokensDelimitedByWhitespace[3:]) if len(dataTokensDelimitedByWhitespace)>=4 else ""
if line.startswith(":"):line=line[1:]
print("'%s'"%line)
p = line.find("news")
if p == -1:
p = line.find("новости")
if p == -1:
pass
else:
p=p+len("новости")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
else:
p = p+len("news")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
if len(kwlist)==0:
self.print_new_runews_newsapi_org(where_mes_exc)
else:
resultUrl = self.news_search_ctxwebsrch(kwlist[0],1)
self.sendmsg(where_mes_exc, "%s" % (resultUrl if resultUrl else "Новостей не найдено"))
if is_uanews_command(bot_nick, str_incoming_line):
if self.grantCommand(sentBy, communicationsLineName):
kwlist = []
where_mes_exc = communicationsLineName
line = " ".join(dataTokensDelimitedByWhitespace[3:]) if len(dataTokensDelimitedByWhitespace)>=4 else ""
if line.startswith(":"):line=line[1:]
print("'%s'"%line)
p = line.find("news")
if p == -1:
p = line.find("новости")
if p == -1:
pass
else:
p=p+len("новости")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
else:
p = p+len("news")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
if len(kwlist)==0:
self.print_new_uanews_newsapi_org(where_mes_exc)
else:
resultUrl = self.news_search_ctxwebsrch(kwlist[0],1)
self.sendmsg(where_mes_exc, "%s" % (resultUrl if resultUrl else "Новостей не найдено"))
def write_quotes(self):
print(__name__, "writing quotes.json")
with open('quotes.json', 'w') as myfile:
myfile.write(json.dumps(self.quotes_array))
def read_quotes(self):
# read file
#try:
print(__name__, "reading quotes.json")
with open('quotes.json', 'r') as myfile:
quotes_array=myfile.read()
self.quotes_array = json.loads(quotes_array)
#except:
# traceback.print_exc()
# print(__name__, "warning: setting empty quotes_array")
# quotes_array = []
#tok1[0] :[email protected]
#tok1[1] PRIVMSG
#tok1[2] #ru
# OR
#tok1[2] BichBot
#tok1[3] :!!aq/!!q
#tok1[4:] tokens
def print_quote(self, tok1):
at = tok1[2]
query = " ".join(tok1[4:])
try:
num = int(query)
except ValueError:
self.sendmsg(at, f"Need a positive int.")
return
if num > 0:
num = num - 1
self.read_quotes()
if num >= len(self.quotes_array):
self.sendmsg(at, f"Max quote number: {len(self.quotes_array)}.")
else:
q = self.quotes_array[num]
poster = q['posted-by'].split("!")[0]
self.sendmsg(at, f"[{num+1}] {q['text']} ({poster} at {q['date-posted']})")
else:
self.sendmsg(at, f"Need a positive int.")
def add_quote(self, tok1):
self.read_quotes()
length = len(self.quotes_array)
quote = " ".join(tok1[4:])
self.quotes_array.append({
"posted-by": tok1[0][1:],
"text": quote,
"date-posted": str(datetime.datetime.now(pytz.utc))
})
at = tok1[2]
self.write_quotes()
self.sendmsg(at, f"Quote added: [{length+1}] {quote}")
pass
def maybe_quotes(self, str_incoming_line, sentBy, commLineName):
tok1 = str_incoming_line.split(" ")
if len(tok1)<3: return False
if tok1[1] != "PRIVMSG": return False
cmdtok = tok1[3].split(":")
if len(cmdtok)<2: return False
cmd = cmdtok[1]
if not cmd.startswith("!!"): return False
if cmd == "!!q":
if self.grantCommand(sentBy, commLineName):
self.print_quote(tok1)
return True
if cmd == "!!aq":
if self.grantCommand(sentBy, commLineName):
self.add_quote(tok1)
return True
return False
def help_make_choice(self, message):
if ' или ' in message:
s = message.split(' или ')
if len(s) > 1:
return choice(s).strip('?')
if message.endswith('?'):
return choice(['да', 'нет'])
return None
def maybe_choice(self, bot_nick, str_incoming_line):
tok1 = str_incoming_line.split(" ")
if len(tok1)<3: return False
if tok1[1] != "PRIVMSG": return False
message = " ".join(tok1[3:])[1:]
if not bot_nick in message: return False
reply = self.help_make_choice(message)
if not reply: return False
at = tok1[2]
self.sendmsg(at, reply)
return True
def maybe_print_search(self, bot_nick, str_incoming_line, sentBy):
dataTokensDelimitedByWhitespace = str_incoming_line.split(" ")
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
if is_search_command(bot_nick, str_incoming_line):
if self.grantCommand(sentBy, communicationsLineName):
kwlist = []
where_mes_exc = communicationsLineName
line = " ".join(dataTokensDelimitedByWhitespace[3:]) if len(dataTokensDelimitedByWhitespace)>=4 else ""
if line.startswith(":"):line=line[1:]
print("'%s'"%line)
p = line.find("search")
if p == -1:
p = line.find("поиск")
if p == -1:
pass
else:
p=p+len("поиск")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
else:
p = p+len("search")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
if len(kwlist)==0:
self.sendmsg(where_mes_exc, "Чего синьорам найти?")
else:
resultUrl = self.web_search(kwlist[0],1)
self.sendmsg(where_mes_exc, "%s" % (resultUrl if resultUrl else "Результатов не найдено"))
def maybe_print_search2(self, bot_nick, str_incoming_line, sentBy, communicationsLineName):
if is_search_command2(bot_nick, str_incoming_line):
if self.grantCommand(sentBy, communicationsLineName):
kwlist = []
dataTokensDelimitedByWhitespace = str_incoming_line.split(" ")
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
where_mes_exc = communicationsLineName
line = " ".join(dataTokensDelimitedByWhitespace[3:]) if len(dataTokensDelimitedByWhitespace)>=4 else ""
if line.startswith(":"):line=line[1:]
print("'%s'"%line)
p = line.find("search2")
if p == -1:
p = line.find("поиск2")
if p == -1:
pass
else:
p=p+len("поиск2")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
else:
p = p+len("search2")
line = line[p:].strip()
print("'%s'"%line)
if line != '': kwlist.append(line)
if len(kwlist)==0:
self.sendmsg(where_mes_exc, "Чего синьорам найти?")
else:
resultUrl = web_search2(kwlist[0],1)
self.sendmsg(where_mes_exc, "%s" % (resultUrl if resultUrl else "Результатов не найдено"))
databuf = b''
socket_closed = False
def init_socket(self, client_socket):
self.databuf = b''
self.socket_closed = False
def extract_line(self):
# socket must be closed for this call.
if not self.socket_closed: raise Exception
a = self.databuf.find(b'\r')
b = self.databuf.find(b'\n')
if a != -1 and b != -1: a = min(a, b)
if b != -1 and a == -1: a = b
if a != -1:
line = self.databuf[0:a]
if self.databuf[a]==0xD:
a=a+1
if a<len(self.databuf) and self.databuf[a]==0xA:
a=a+1
else:
if self.databuf[a]==0xA:
a=a+1
self.databuf = self.databuf[a:] if a < len(self.databuf) else b''
return line
return self.databuf
def extract_line_1(self):
#if LOG_TRACE: print("extract_line_1() #0: databuf", databuf, "socket_closed", socket_closed)
a = self.databuf.find(b'\r')
b = self.databuf.find(b'\n')
if a != -1 and b != -1: a = min(a, b)
if b != -1 and a == -1: a = b
if a != -1:
if LOG_TRACE: print("#1: a:", a, "len(databuf):", len(self.databuf), "databuf[a]==b'SLASHr':", self.databuf[a]==0xD, "databuf[a]:", self.databuf[a], "a < len(databuf)-1:", a < len(self.databuf)-1)
if (self.databuf[a]==0xD and a < len(self.databuf)-1) or self.databuf[a]==0xA:
if LOG_TRACE: print("#2")
line = self.databuf[0:a]
if self.databuf[a]==0xD:
if LOG_TRACE: print("#3")
a=a+1
if self.databuf[a]==0xA:
if LOG_TRACE: print("#4")
a=a+1
else:
if LOG_TRACE: print("#5")
if self.databuf[a]==0xA:
if LOG_TRACE: print("#6")
a=a+1
if LOG_TRACE: print("#7, a:", a)
self.databuf = self.databuf[a:]
if LOG_TRACE: print("returning line:", line)
return line
#else read more
#else read more
if LOG_TRACE: print("returning None")
return None
def get_line(self, client_socket):
if self.socket_closed:
return self.extract_line()
line = self.extract_line_1()
if line is not None: return line
while True:
r = client_socket.recv(81920)
if len(r) == 0:
if LOG_TRACE: print("EOF")
self.socket_closed = True
return self.extract_line()
if LOG_TRACE: print("RX:", r)
self.databuf += r
line = self.extract_line_1()
if line is not None: return line
# Function shortening of ic.self.send.
def send(self, msg):
print(f"TX: {msg}")
retval = self.irc_socket.send(bytes(msg,'utf-8'))
return retval
# Install min & max timer vote.
min_timer = 30
max_timer = 300
def get_news_count_for_channel(self, commLineName):
props = self.channelsProps[commLineName] if commLineName in self.channelsProps else None
if props is None: return 10
return props['news_count'] if 'news_count' in props else 3
def pinger_of_server(self):
print ("spawned pinger_of_server, key: '%s'" % self.settings_key)
while True:
print("---new ping to server---")
self.pong_received=False
self.send('PING :'+str(time.time())+'\r\n')
time.sleep(180)
if self.pong_received:
continue
else:
print ("ping to server timeout, closing socket, key: '%s'" % self.settings_key)
self.irc_socket.close()
print ("exiting pinger of server, key: '%s'" % self.settings_key)
return
def login_and_loop(self):
while True:
print("---new iter---", flush=True)
try:
mask2ctx = {}
from time import sleep as sleep_seconds
print("sleeping 50ms...")
sleep_seconds(0.05)
if self.connection_setting_or_None('socks5_host'):
host = self.connection_option('socks5_host')
print (f"new socks.socksocket({host})")
self.irc_socket = socks.socksocket()
self.irc_socket.set_proxy(socks.SOCKS5, host, \
self.connection_option('socks5_port'), True, self.connection_option('socks5_username'), \
self.connection_option('socks5_password'))
else:
print ("new socket(AF_INET,SOCK_STREAM)")
self.irc_socket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print("connecting... irc_server_hostname='"+self.irc_server_hostname+"' port='"+str(self.port)+"'…")
self.irc_socket.connect ((self.irc_server_hostname, self.port))
self.init_socket(self.irc_socket)
print("connected, self.sending login handshake, self.botName=["+self.botName+"]…")
#print (self.irc_socket.recv(2048).decode("UTF-8"))
self.send('NICK '+self.botName+'\r\n')
self.send('USER '+self.botName+' '+self.botName+' '+self.botName+' :irc bot\r\n')
#self.send('NickServ IDENTIFY '+settings.settings('password')+'\r\n')
#self.send('MODE '+self.botName+' +x')
name = ''
message = ''
message_voting = ''
voting_results = ''
count_voting = 0
count_vote_plus = 0
count_vote_minus = 0
count_vote_all = 0
while_count = 0
btc_usd = 0
eth_usd = 0
usd_rub = 0
eur_rub = 0
btc_rub = 0
btc_usd_old = 0
eth_usd_old = 0
usd_rub_old = 0
eur_rub_old = 0
btc_rub_old = 0
btc_usd_su = ''
eth_usd_su = ''
usd_rub_su = ''
eur_rub_su = ''
time_vote = 0
whois_ip = ''
whois_ip_get_text = ''
timer_exc = 0
time_exc = 0
where_mes_exc = ''
t2 = 0
dict_users = {}
dict_count = {}
dict_voted = {}
list_vote_ip = []
# List who free from anti-flood function.
list_floodfree = settings.settings('list_floodfree')
list_bot_not_work = settings.settings('list_bot_not_work')
keepingConnection=True
while keepingConnection:
try:
data = self.get_line(self.irc_socket).decode("UTF-8")
print("got line:["+data+"]", flush=True)
if data=="":
print("data=='', self.irc_socket.close(), keepingConnection=False, iterating...");
self.irc_socket.close()
keepingConnection=False
continue
except UnicodeDecodeError as decodeException:
print(f"UnicodeDecodeError {decodeException}, iterating...")
continue
tokens1 = data.split(" ");
sender_mask = None
dataTokensDelimitedByWhitespace = tokens1
#dataTokensDelimitedByWhitespace[0] :[email protected]
#dataTokensDelimitedByWhitespace[1] PRIVMSG
#dataTokensDelimitedByWhitespace[2] #ru
# OR
#dataTokensDelimitedByWhitespace[2] BichBot
#dataTokensDelimitedByWhitespace[3] :!курс
communicationsLineName = dataTokensDelimitedByWhitespace[2] if len(dataTokensDelimitedByWhitespace) > 2 else None
lineJoined = " ".join(dataTokensDelimitedByWhitespace[3:]) if len(dataTokensDelimitedByWhitespace) >= 4 else ""
sender = communicationsLineName
sentBy = dataTokensDelimitedByWhitespace[0][1:]
if len(tokens1)>1 and tokens1[1]=="433": #"Nickname is already in use" in data
self.botNickSalt=self.botNickSalt+1
self.botName = self.BOT_NAME_PREFIX+str(self.botNickSalt)
self.send('NICK '+self.botName+'\r\n')
continue
if len(tokens1)>=4 and tokens1[1]=="MODE" and "+x" in tokens1[3]: #:GreenBich MODE GreenBich :+x
self.send('JOIN '+(",".join(self.channelsList))+' \r\n')
continue
#
if self.nickserv_password is not None and len(tokens1)>1 and tokens1[1]=="001": #001 nick :Welcome to the Internet Relay Network
self.send('NICKSERV IDENTIFY '+self.nickserv_password+'\r\n')
if data.find('PING') != -1:
try:
print("ping_received")
self.send('PONG '+data.split(" ")[1]+'\r\n')
print("pong sent with data_str")
except:
traceback.print_exc()
self.send('PONG')
print("pong sent without data_str")
continue
if data.find('PONG') != -1:
print("server pong_received")
self.pong_received=True
continue
#001 welcome
spws = tokens1
if len(spws) > 1 and spws[1]=="001":
MyPingsToServerThread(self).start()
self.send('MODE '+self.botName+' +xB\r\n')
continue
ws_tokens = tokens1
try:
message = None
#got line:[:test2!~username@ipaddr PRIVMSG #channel :msg]
if len(ws_tokens)>=4:
src = ws_tokens[0]
cmd = ws_tokens[1]
chan = ws_tokens[2]
msg = " ".join(ws_tokens[3:])
if cmd == "PRIVMSG":
name = src.split('!')[0][1:]
sender_mask = src[1:]
message = msg[1:]
print(__name__, f"message: '{message}'",flush=True)
try:
ip_user=None#"data.split('@',1)[1].split(' ',1)[0]
except:
print(__name__, 'error getting ip_user')
except:
import traceback as tb