forked from Whalepool/Natalia
-
Notifications
You must be signed in to change notification settings - Fork 1
/
natalia.py
1498 lines (1056 loc) · 45.4 KB
/
natalia.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
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# A Simple way to send a message to telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler
from telegram import MessageEntity, TelegramObject, ChatAction
from pprint import pprint
from functools import wraps
from future.builtins import bytes
from pymongo import MongoClient
from pathlib import Path
import numpy as np
import argparse
import logging
import telegram
import sys
import json
import random
import datetime
from dateutil.relativedelta import relativedelta
import re
import os
import sys
import yaml
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from PIL import Image
# For plotting messages / price charts
import pandas as pd
import requests
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle, Patch
from mpl_finance import candlestick_ohlc
import talib as ta
PATH = os.path.dirname(os.path.abspath(__file__))
"""
# Configure Logging
"""
FORMAT = '%(asctime)s -- %(levelname)s -- %(module)s %(lineno)d -- %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger('root')
logger.info("Running "+sys.argv[0])
"""
# Mongodb
"""
client = MongoClient('mongodb://localhost:27017')
db = client.natalia_tg_bot
"""
# Load the config file
# Set the Botname / Token
"""
config_file = PATH+'/config.yaml'
my_file = Path(config_file)
if my_file.is_file():
with open(config_file) as fp:
config = yaml.load(fp)
else:
pprint('config.yaml file does not exists. Please make from config.sample.yaml file')
sys.exit()
BOTNAME = config['NATALIA_BOT_USERNAME']
TELEGRAM_BOT_TOKEN = config['NATALIA_BOT_TOKEN']
FORWARD_PRIVATE_MESSAGES_TO = config['BOT_OWNER_ID']
ADMINS = config['ADMINS']
EXTRA_STOPWORDS = config['WORDCLOUD_STOPWORDS']
FORWARD_URLS = r""+config['FORWARD_URLS']
SHILL_DETECTOR = r""+config['SHILL_DETECTOR']
COUNTER_SHILL = []
for s in config['COUNTER_SHILL']:
COUNTER_SHILL.append({
'title': s['title'],
'regex': r""+s['match'],
'link' : s['link']
})
MESSAGES = {}
MESSAGES['welcome'] = config['MESSAGES']['welcome']
#MESSAGES['welcomewomen'] = config['MESSAGES']['welcome_special']
MESSAGES['goodbye'] = config['MESSAGES']['goodbye']
MESSAGES['pmme'] = config['MESSAGES']['pmme']
MESSAGES['start'] = config['MESSAGES']['start']
MESSAGES['admin_start'] = config['MESSAGES']['admin_start']
MESSAGES['about'] = config['MESSAGES']['about']
MESSAGES['rules'] = config['MESSAGES']['rules']
#MESSAGES['teamspeak'] = config['MESSAGES']['teamspeak']
#MESSAGES['telegram'] = config['MESSAGES']['telegram']
MESSAGES['chat'] = config['MESSAGES']['chat']
#MESSAGES['livestream'] = config['MESSAGES']['livestream']
MESSAGES['exchanges'] = config['MESSAGES']['exchanges']
MESSAGES['shill'] = config['MESSAGES']['shill']
#MESSAGES['teamspeakbadges'] = config['MESSAGES']['teamspeakbadges']
#MESSAGES['fomobot'] = config['MESSAGES']['fomobot']
#MESSAGES['donate'] = config['MESSAGES']['donate']
ADMINS_JSON = config['MESSAGES']['admins_json']
# Rooms
WP_ROOM = -1001103012181 # Neblio Main Channel
WP_ROOM2 = -1001149607483 # Neblio Multilingual
#SP_ROOM = -1001120581521 # Shitpool
WP_ADMIN = -279751667 # Neblio Staff Room
#MH_ROOM = -1001213548615 # Master Holder room
#TEST_ROOM = -1001223115449 # Test room
#WP_WOMENS = -1001248205448 # Whalepool Womens
#WP_FEED = "@whalepoolbtcfeed" # Whalepool Feed
#SP_FEED = "@shitcoincharts" # shitpool feed
ROOM_ID_TO_NAME = {
WP_ROOM : 'Neblio - Official',
WP_ROOM2 : 'Neblio - Multilingual',
#SP_ROOM : 'Shitpool',
WP_ADMIN: 'Neblio Staff Room',
#MH_ROOM : 'Whalepool Trading Dojo',
#TEST_ROOM: 'Test room',
#WP_WOMENS : 'Whalepool Womens',
#WP_FEED : 'Whalepool Feed channel',
#SP_FEED : 'Shitpool Feed channel'
}
# Rooms where chat/gifs/etc is logged for stats etc
#LOG_ROOMS = [ WP_ROOM, SP_ROOM, TEST_ROOM ]
LOG_ROOMS = [ WP_ROOM, WP_ROOM2 ]
# Storing last 'welcome' message ids
PRIOR_WELCOME_MESSAGE_ID = {
WP_ROOM : 0,
WP_ROOM2 : 0,
#SP_ROOM : 0,
#MH_ROOM : 0,
#TEST_ROOM : 0,
#WP_WOMENS : 0
}
# Storing last 'removal' of uncompress images, message ids
LASTUNCOMPRESSED_IMAGES = {
WP_ROOM : 0,
WP_ROOM2 : 0
#SP_ROOM : 0,
#MH_ROOM : 0,
#TEST_ROOM : 0,
#WP_WOMENS : 0
}
# Hashtags that forward messages to specific channels
#forward_hashtags = {
# '#communityfund' : WP_FEED,
# '#community' : WP_FEED
#}
#################################
# Begin bot..
bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN)
# Bot error handler
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
# Restrict bot functions to admins
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in ADMINS:
print("Unauthorized access denied for {}.".format(user_id))
return
return func(bot, update, *args, **kwargs)
return wrapped
#################################
# UTILS
# Resolve message data to a readable name
def get_name(update):
try:
name = update.message.from_user.first_name
except (NameError, AttributeError):
try:
name = update.message.from_user.username
except (NameError, AttributeError):
logger.info("No username or first name.. wtf")
return ""
return name
#################################
# BEGIN BOT COMMANDS
# Returns the user their user id
def getid(bot, update):
pprint(update.message.chat.__dict__, indent=4)
update.message.reply_text(str(update.message.chat.first_name)+" :: "+str(update.message.chat.id))
# Welcome message
def start(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
user_id = update.message.from_user.id
name = get_name(update)
logger.info("/start - "+name)
pprint(update.message.chat.type)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['rules']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'start', 'timestamp': timestamp }
db.pm_requests.insert(info)
msg = bot.sendMessage(chat_id=chat_id, text=(MESSAGES['start'] % name),parse_mode="Markdown",disable_web_page_preview=1)
if user_id in ADMINS:
msg = bot.sendMessage(chat_id=chat_id, text=(MESSAGES['admin_start'] % name),parse_mode="Markdown",disable_web_page_preview=1)
def about(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/about - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['about']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'about', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def rules(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/rules - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['rules']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'rules', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def admins(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/admins - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = "*Neblio Admins*\n\n"
keys = list(ADMINS_JSON.keys())
random.shuffle(keys)
for k in keys:
msg += ""+k+"\n"
msg += ADMINS_JSON[k]['adminOf']+"\n"
msg += "_"+ADMINS_JSON[k]['about']+"_"
msg += "\n\n"
msg += "/start - to go back to home"
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'admins', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def teamspeak(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/teamspeak - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['teamspeak']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'teamspeak', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendSticker(chat_id=chat_id, sticker="CAADBAADqgIAAndCvAiTIPeFFHKWJQI", disable_notification=False)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def teamspeakbadges(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/teamspeakbadges - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['teamspeakbadges']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'teamspeakbadges', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def telegram(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/telegram - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['telegram']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'telegram', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def chat(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/chat - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['chat']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'chat', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def livestream(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/livestream - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['livestream']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'livestream', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendSticker(chat_id=chat_id, sticker="CAADBAADcwIAAndCvAgUN488HGNlggI", disable_notification=False)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def fomobot(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/fomobot - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['fomobot']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'fomobot', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
def exchanges(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/exchanges - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
msg = MESSAGES['exchanges']
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'exchanges', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendMessage(chat_id=chat_id,text=msg,parse_mode="Markdown",disable_web_page_preview=1)
# bot.forwardMessage(chat_id=WP_ADMIN, from_chat_id=chat_id, message_id=message_id)
def donation(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
message_id = update.message.message_id
name = get_name(update)
logger.info("/donation - "+name)
if (update.message.chat.type == 'group') or (update.message.chat.type == 'supergroup'):
msg = random.choice(MESSAGES['pmme']) % (name)
bot.sendMessage(chat_id=chat_id,text=msg,reply_to_message_id=message_id, parse_mode="Markdown",disable_web_page_preview=1)
else:
timestamp = datetime.datetime.utcnow()
info = { 'user_id': user_id, 'request': 'donation', 'timestamp': timestamp }
db.pm_requests.insert(info)
bot.sendPhoto(chat_id=chat_id, photo="AgADBAADlasxG4uhCVPAkVD5G4AaXgtKXhkABL8N5jNhPaj1-n8CAAEC",caption="Donations by bitcoin to: 175oRbKiLtdY7RVC8hSX7KD69WQs8PcRJA")
####################################################
# ADMIN FUNCTIONS
@restricted
def topstickers(bot,update):
user_id = update.message.from_user.id
chat_id = update.message.chat.id
start = datetime.datetime.today().replace(hour=0,minute=0,second=0)
start = start - relativedelta(days=3)
pipe = [
{ "$match": { 'timestamp': {'$gt': start } } },
{ "$group": { "_id": "$sticker_id", "total": { "$sum": 1 } } },
{ "$sort": { "total": -1 } },
{ "$limit": 3 }
]
gifs = list(db.natalia_stickers.aggregate(pipe))
bot.sendMessage(chat_id=update.message.chat_id, text="Posting... sometimes this can cause the telegram api to 'time out' ? so won't complete posting but trying anyway.." )
bot.sendMessage(chat_id=WP_ROOM, text="Whalepool most popular 3 stickers in the last 3 days are..." )
for g in gifs:
pprint(g)
bot.sendMessage(chat_id=WP_ROOM, text="with "+str(g['total'])+" posts..")
bot.sendSticker(chat_id=WP_ROOM, sticker=g['_id'], disable_notification=False)
time.sleep(5)
bot.sendMessage(chat_id=update.message.chat_id, text="message has been posted to "+ROOM_ID_TO_NAME[WP_ROOM] )
@restricted
def topgif(bot,update):
chat_id = update.message.chat.id
pipe = [ { "$group": { "_id": "$file_id", "total": { "$sum": 1 } } }, { "$sort": { "total": -1 } }, { "$limit": 5 } ]
gifs = list(db.natalia_gifs.aggregate(pipe))
bot.sendMessage(chat_id=WP_ROOM, text="Whalepool most popular gif ever with "+str(gifs[0]['total'])+" posts is..." )
bot.sendSticker(chat_id=WP_ROOM, sticker=gifs[0]['_id'], disable_notification=False)
bot.sendMessage(chat_id=chat_id, text="message has been posted to "+ROOM_ID_TO_NAME[WP_ROOM] )
@restricted
def topgifposters(bot, update):
chat_id = update.message.chat.id
pipe = [ { "$group": { "_id": "$user_id", "total": { "$sum": 1 } } }, { "$sort": { "total": -1 } }, { "$limit": 5 } ]
users = list(db.natalia_gifs.aggregate(pipe))
msg = "I'm naming and shaming the top 5 gif posters in "+ROOM_ID_TO_NAME[WP_ROOM]
for i,u in enumerate(users):
user = list(db.users.find({ 'user_id': u['_id'] }))
if len(user) > 0:
user = user[0]
msg += "\n#"+str(i+1)+" - "+user['name']+" with "+str(u['total'])+" gifs"
msg = bot.sendMessage(chat_id=WP_ROOM, text=msg )
bot.forwardMessage(chat_id=chat_id, from_chat_id=WP_ROOM, message_id=msg.message_id)
bot.sendMessage(chat_id=chat_id, text="message has been posted to "+ROOM_ID_TO_NAME[WP_ROOM] )
@restricted
def todayinwords(bot, update):
chat_id = update.message.chat.id
logger.info("Today in words..")
logger.info("Fetching from db...")
start = datetime.datetime.today().replace(hour=0,minute=0,second=0)
pipe = { '_id': 0, 'message': 1 }
msgs = list(db.natalia_textmessages.find({ 'timestamp': {'$gt': start } }, pipe ))
words = []
for w in msgs:
results = re.findall(r"(.*(?=:)): (.*)", w['message'])[0]
words.append(results[1].strip())
extra_stopwords = EXTRA_STOPWORDS
for e in extra_stopwords:
STOPWORDS.add(e)
stopwords = set(STOPWORDS)
logger.info("Building comments pic...")
# Happening today
wc = WordCloud(background_color="white", max_words=2000, stopwords=stopwords, relative_scaling=0.2,scale=3)
# generate word cloud
wc.generate(' '.join(words))
# store to file
PATH_WORDCLOUD = PATH+"talkingabout_wordcloud.png"
wc.to_file(PATH_WORDCLOUD)
msg = bot.sendPhoto(chat_id=WP_ROOM, photo=open(PATH_WORDCLOUD,'rb'), caption="Today in a picture" )
bot.sendMessage(chat_id=chat_id, text="Posted today in pictures to "+ROOM_ID_TO_NAME[WP_ROOM] )
os.remove(PATH_WORDCLOUD)
@restricted
def todaysusers(bot, update):
chat_id = update.message.chat.id
bot.sendMessage(chat_id=chat_id, text="Okay gimme a second for this one.. it takes some resources.." )
logger.info("Today in words..")
logger.info("Fetching from db...")
start = datetime.datetime.today().replace(hour=0,minute=0,second=0)
pipe = { '_id': 0, 'message': 1 }
msgs = list(db.natalia_textmessages.find({ 'timestamp': {'$gt': start } }, pipe ))
usernames = []
for w in msgs:
results = re.findall(r"(.*(?=:)): (.*)", w['message'])[0]
usernames.append(results[0].strip())
extra_stopwords = EXTRA_STOPWORDS
for e in extra_stopwords:
STOPWORDS.add(e)
stopwords = set(STOPWORDS)
logger.info("Building usernames pic...")
PATH_MASK = PATH+"media/wp_background_mask2.png"
PATH_BG = PATH+"media/wp_background.png"
PATH_USERNAMES = PATH+"telegram-usernames.png"
# Usernames
d = os.path.dirname('__file__')
mask = np.array(Image.open(PATH_MASK))
wc = WordCloud(background_color=None, max_words=2000,mask=mask,colormap='BuPu',
stopwords=stopwords,mode="RGBA", width=800, height=400)
wc.generate(' '.join(usernames))
wc.to_file(PATH_USERNAMES)
layer1 = Image.open(PATH_BG).convert("RGBA")
layer2 = Image.open(PATH_USERNAMES).convert("RGBA")
Image.alpha_composite(layer1, layer2).save(PATH_USERNAMES)
msg = bot.sendPhoto(chat_id=WP_ROOM, photo=open("telegram-usernames.png",'rb'), caption="Todays Users" )
bot.sendMessage(chat_id=chat_id, text="Posted today in pictures to "+ROOM_ID_TO_NAME[WP_ROOM] )
os.remove(PATH_USERNAMES)
@restricted
def promotets(bot, update):
pprint('promotets...')
chat_id = update.message.chat_id
name = get_name(update)
fmsg = re.findall( r"\"(.*?)\"", update.message.text)
if len(fmsg) > 0:
rooms = [WP_ROOM]
#rooms = [WP_ROOM, SP_ROOM, MH_ROOM, WP_FEED, SP_FEED]
for r in rooms:
message = fmsg[0]
bot.sendSticker(chat_id=r, sticker="CAADBAADcwIAAndCvAgUN488HGNlggI", disable_notification=False)
msg = bot.sendMessage(chat_id=r, parse_mode="Markdown", text=fmsg[0]+"\n-------------------\n*/announcement from "+name+"*" )
#if r in [WP_ROOM, SP_ROOM, MH_ROOM]:
if r in [WP_ROOM]:
bot.pin_chat_message(r, msg.message_id, disable_notification=True)
bot.sendMessage(chat_id=r, parse_mode="Markdown", text="Message me ("+BOTNAME.replace('_','\_')+") - to see details on how to connect to [teamspeak](https://whalepool.io/connect/teamspeak) also listen in to the listream here: livestream.whalepool.io", disable_web_page_preview=True )
bot.sendMessage(chat_id=chat_id, parse_mode="Markdown", text="Broadcast sent to "+ROOM_ID_TO_NAME[r])
else:
bot.sendMessage(chat_id=chat_id, text="Please incldue a message in quotes to spam/shill the teamspeak message" )
@restricted
def shill(bot, update):
chat_id = update.message.chat_id
name = get_name(update)
bot.sendMessage(chat_id=WP_ADMIN, parse_mode="Markdown", text=name+" just shilled")
#rooms = [WP_ROOM, SP_ROOM, WP_FEED, SP_FEED]
rooms = [WP_ROOM]
for r in rooms:
bot.sendMessage(chat_id=r, parse_mode="Markdown", text=MESSAGES['shill'],disable_web_page_preview=1)
bot.sendMessage(chat_id=chat_id, parse_mode="Markdown", text="Shilled in "+ROOM_ID_TO_NAME[r])
@restricted
def commandstats(bot, update):
chat_id = update.message.chat_id
start = datetime.datetime.today().replace(day=1,hour=0,minute=0,second=0)
# start = start - relativedelta(days=30)
pipe = [
{ "$match": { 'timestamp': {'$gt': start } } },
{ "$group": {
"_id": {
"year" : { "$year" : "$timestamp" },
"month" : { "$month" : "$timestamp" },
"day" : { "$dayOfMonth" : "$timestamp" },
"request": "$request"
},
"total": { "$sum": 1 }
}
},
{ "$sort": { "total": -1 } },
# { "$limit": 3 }
]
res = list(db.pm_requests.aggregate(pipe))
output = {}
totals = {}
for r in res:
key = r['_id']['day']
if not(key in output):
output[key] = {}
request = r['_id']['request']
if not(request in output[key]):
output[key][r['_id']['request']] = 0
if not(request in totals):
totals[request] = 0
output[key][r['_id']['request']] += r['total']
totals[request] += r['total']
reply = "*Natalia requests since the start of the month...*\n"
for day in sorted(output.keys()):
reply += "--------------------\n"
reply += "*"+str(day)+"*\n"
for request, count in output[day].items():
reply += request+" - "+str(count)+"\n"
reply += "--------------------\n"
reply += "*Totals*\n"
for request in totals:
reply += request+" - "+str(totals[request])+"\n"
bot.sendMessage(chat_id=chat_id, text=reply, parse_mode="Markdown" )
@restricted
def joinstats(bot,update):
chat_id = update.message.chat_id
start = datetime.datetime.today().replace(day=1,hour=0,minute=0,second=0)
# start = start - relativedelta(days=30)
pipe = [
{ "$match": { 'timestamp': {'$gt': start } } },
{ "$group": {
"_id": {
"day" : { "$dayOfMonth" : "$timestamp" },
"chat_id": "$chat_id"
},
"total": { "$sum": 1 }
}
},
{ "$sort": { "total": -1 } },
# { "$limit": 3 }
]
res = list(db.room_joins.aggregate(pipe))
output = {}
totals = {}
for r in res:
key = r['_id']['day']
if not(key in output):
output[key] = {}
roomid = r['_id']['chat_id']
if not(roomid in output[key]):
output[key][roomid] = 0
if not(roomid in totals):
totals[roomid] = 0
output[key][roomid] += r['total']
totals[roomid] += r['total']
reply = "*Channel Joins since the start of the month...*\n"
for day in sorted(output.keys()):
reply += "--------------------\n"
reply += "*"+str(day)+"*\n"
for room, count in output[day].items():
reply += ROOM_ID_TO_NAME[room]+" - "+str(count)+"\n"
reply += "--------------------\n"
reply += "*Totals*\n"
for roomid in totals:
reply += ROOM_ID_TO_NAME[roomid]+" - "+str(totals[roomid])+"\n"
bot.sendMessage(chat_id=chat_id, text=reply, parse_mode="Markdown" )
def fooCandlestick(ax, quotes, width=0.029, colorup='#FFA500', colordown='#222', alpha=1.0):
OFFSET = width/2.0
lines = []
boxes = []
for q in quotes:
timestamp, op, hi, lo, close = q[:5]
box_h = max(op, close)
box_l = min(op, close)
height = box_h - box_l
if close>=op:
color = '#3fd624'
else:
color = '#e83e2c'
vline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
vline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
rect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10)
rect.set_alpha(alpha)
lines.append(vline_lo)
lines.append(vline_hi)
boxes.append(rect)
ax.add_line(vline_lo)
ax.add_line(vline_hi)
ax.add_patch(rect)
ax.autoscale_view()
return lines, boxes
# Special function for testing purposes
@restricted
def whalepooloverprice(bot, update):
user_id = update.message.from_user.id
chat_id = update.message.chat_id
bot.sendMessage(chat_id=61697695, text="Processing data" )
# Room only
mongo_match = { "$match": { 'chat_id': WP_ROOM } }
do = 'hourly'
if do == 'daily':
bar_width = 0.864
api_timeframe = '1D'
date_group_format = "%Y-%m-%d"
if do == 'hourly':
bar_width = 0.029
api_timeframe = '1h'
date_group_format = "%Y-%m-%dT%H"
# Get the candles
url = 'https://api.bitfinex.com/v2/candles/trade:'+api_timeframe+':tBTCUSD/hist?limit=200'
request = json.loads(requests.get(url).text)
candles = pd.read_json(json.dumps(request))
candles.rename(columns={0:'date', 1:'open', 2:'close', 3:'high', 4:'low', 5:'volume'}, inplace=True)
candles['date'] = pd.to_datetime( candles['date'], unit='ms' )
candles.set_index(candles['date'], inplace=True)
candles.sort_index(inplace=True)
first_candlestick_date = candles.index[0].to_pydatetime()
del candles['date']
candles = candles.reset_index()[['date','open','high','low','close','volume']]
candles['date'] = candles['date'].map(mdates.date2num)
# Users joins
pipe = [
mongo_match,
{ "$group": {
"_id": { "$dateToString": { "format": date_group_format, "date": "$timestamp" } },
"count": { "$sum": 1 }
}
},
]
rows = list(db.room_joins.aggregate(pipe))
userjoins = pd.DataFrame(rows)
userjoins['date'] = pd.to_datetime( userjoins['_id'], format=date_group_format)
# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')
del userjoins['_id']
userjoins.set_index(userjoins['date'], inplace=True)
userjoins.sort_index(inplace=True)
userjoins['date'] = userjoins['date'].map(mdates.date2num)
userjoins = userjoins.loc[first_candlestick_date:]
# Get the messages
pipe = [
mongo_match,
{ "$group": {
"_id": { "$dateToString": { "format": date_group_format, "date": "$timestamp" } },
"count": { "$sum": 1 }
}
},
]
rows = list(db.natalia_textmessages.aggregate(pipe))
msgs = pd.DataFrame(rows)
msgs['date'] = pd.to_datetime( msgs['_id'], format=date_group_format)
# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')
del msgs['_id']
msgs.set_index(msgs['date'], inplace=True)
msgs.sort_index(inplace=True)
msgs['date'] = msgs['date'].map(mdates.date2num)
msgs = msgs.loc[first_candlestick_date:]
# Stickers
pipe = [
mongo_match,
{ "$group": {
"_id": { "$dateToString": { "format": date_group_format, "date": "$timestamp" } },
"count": { "$sum": 1 }
}
},
]
rows = list(db.natalia_stickers.aggregate(pipe))
gifs = pd.DataFrame(rows)
gifs['date'] = pd.to_datetime( gifs['_id'], format='%Y-%m-%dT%H')
# msgs['date'] = pd.to_datetime( msgs['_id'], format='%Y-%m-%d')
del gifs['_id']
gifs.set_index(gifs['date'], inplace=True)
gifs.sort_index(inplace=True)
gifs['date'] = gifs['date'].map(mdates.date2num)
gifs = gifs.loc[first_candlestick_date:]
# Enable a Grid
plt.rc('axes', grid=True)
# Set Grid preferences
plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)
# Create a figure, 16 inches by 12 inches
fig = plt.figure(facecolor='white', figsize=(22, 12), dpi=100)
# Draw 3 rectangles
# left, bottom, width, height
left, width = 0.1, 1
rect1 = [left, 0.7, width, 0.5]
rect2 = [left, 0.5, width, 0.2]
rect3 = [left, 0.3, width, 0.2]
rect4 = [left, 0.1, width, 0.2]
ax1 = fig.add_axes(rect1, facecolor='#f6f6f6')
ax2 = fig.add_axes(rect2, facecolor='#f6f6f6', sharex=ax1)
ax3 = fig.add_axes(rect3, facecolor='#f6f6f6', sharex=ax1)
ax4 = fig.add_axes(rect4, facecolor='#f6f6f6', sharex=ax1)
ax1 = fig.add_axes(rect1, facecolor='#f6f6f6')
ax1.set_xlabel('date')
ax1.set_title('Whalepool Messages, Gif & User joins per hour over price', fontsize=20, fontweight='bold')
ax1.xaxis_date()
fooCandlestick(ax1, candles.values, width=bar_width, colorup='g', colordown='k',alpha=0.9)
# fooCandlestick(ax2, candles.values, width=0.864, colorup='g', colordown='k',alpha=0.9)
ax1.set_ylabel('Bitcoin Price', color='g', size='large')
fig.autofmt_xdate()