forked from iranzo/stampython
/
stampy.py
executable file
·1367 lines (1148 loc) · 42.3 KB
/
stampy.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/bin/env python
# encoding: utf-8
#
# Description: Bot for controlling karma on Telegram
# Author: Pablo Iranzo Gomez (Pablo.Iranzo@gmail.com)
#
#
# This program 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, version 2 of the License.
#
# This program 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.
import datetime
import json
import logging
import optparse
import sqlite3 as lite
import string
import sys
import time
import urllib
from time import sleep
from prettytable import from_db_cursor
description = """
Stampy is a script for controlling Karma via Telegram.org bot api
"""
# Option parsing
p = optparse.OptionParser("stampy.py [arguments]", description=description)
p.add_option("-t", "--token", dest="token",
help="API token for bot access to messages", default=False)
p.add_option("-b", "--database", dest="database",
help="database file for storing karma and last processed message",
default="stampy.db")
p.add_option('-v', "--verbosity", dest="verbosity",
help="Set verbosity level for messages while running/logging", default=0, type='choice',
choices=["info", "debug", "warn", "critical"])
p.add_option('-u', "--url", dest="url",
help="Define URL for accessing bot API",
default="https://api.telegram.org/bot")
p.add_option('-o', '--owner', dest='owner',
help="Define owner username for monitoring service", default="iranzo")
p.add_option('-d', '--daemon', dest='daemon', help="Run as daemon",
default=False, action="store_true")
(options, args) = p.parse_args()
# Implement switch from http://code.activestate.com/recipes/410692/
class Switch(object):
"""
Defines a class that can be used easily as traditional switch commands
"""
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
def createdb():
"""
Create database if it doesn't exist
:return:
"""
cur.execute('CREATE TABLE karma(word TEXT, value INT);')
cur.execute('CREATE TABLE alias(key TEXT, value TEXT);')
cur.execute('CREATE TABLE config(key TEXT, value TEXT);')
cur.execute('CREATE TABLE stats(type TEXT, id INT, name TEXT, date TEXT, count INT, users INT);')
cur.execute('CREATE TABLE quote(id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, date TEXT, text TEXT);')
return
# Initialize database access
con = False
try:
con = lite.connect(options.database)
cur = con.cursor()
cur.execute("SELECT * FROM config WHERE key='token';")
data = cur.fetchone()
except lite.Error, e:
createdb()
print "Error %s:" % e.args[0]
print "DB has been created, please, execute again"
sys.exit(1)
# Database initialized
# Function definition
def dbsql(sql=False):
"""
Performs SQL operation on database
:param sql: sql command to execute
:return:
"""
logger = logging.getLogger(__name__)
if sql:
try:
cur.execute(sql)
con.commit()
worked = True
except:
worked = False
if not worked:
logger.critical(msg="Error on SQL execution: %s" % sql)
return worked
def sendmessage(chat_id=0, text="", reply_to_message_id=False, disable_web_page_preview=True, parse_mode=False,
extra=False):
"""
Sends a message to a chat
:param chat_id: chat_id to receive the message
:param text: message text
:param reply_to_message_id: message_id to reply
:param disable_web_page_preview: do not expand links to include page preview
:param parse_mode: use specific format (markdown, html)
:param extra: extra parameters to send (for future functions like keyboard_markup)
:return:
"""
logger = logging.getLogger(__name__)
url = "%s%s/sendMessage" % (config(key="url"), config(key='token'))
lines = text.split("\n")
maxlines = 15
if len(lines) > maxlines:
# message might be too big for single message (max 4K)
if "```" in text:
markdown = True
else:
markdown = False
texto = string.join(lines[0:maxlines], "\n")
if markdown:
texto = "%s```" % texto
# Send first batch
sendmessage(chat_id=chat_id, text=texto, reply_to_message_id=reply_to_message_id,
disable_web_page_preview=disable_web_page_preview, parse_mode=parse_mode, extra=extra)
# Send remaining batch
texto = string.join(lines[maxlines:], "\n")
if markdown:
texto = "```%s" % texto
sendmessage(chat_id=chat_id, text=texto, reply_to_message_id=False,
disable_web_page_preview=disable_web_page_preview, parse_mode=parse_mode, extra=extra)
return
message = "%s?chat_id=%s&text=%s" % (url, chat_id,
urllib.quote_plus(text.encode('utf-8'))
)
if reply_to_message_id:
message += "&reply_to_message_id=%s" % reply_to_message_id
if disable_web_page_preview:
message += "&disable_web_page_preview=1"
if parse_mode:
message += "&parse_mode=%s" % parse_mode
if extra:
message += "&%s" % extra
code = False
while not code:
result = json.load(urllib.urlopen(message))
code = result['ok']
logger.error(msg="ERROR sending message: Code: %s : Text: %s" % (code, result))
sleep(1)
logger.debug(msg="Sending message: Code: %s : Text: %s" % (code, text))
return
def getupdates(offset=0, limit=100):
"""
Gets updates (new messages from server)
:param offset: last update id
:param limit: maximum number of messages to gather
:return: returns the items obtained
"""
logger = logging.getLogger(__name__)
url = "%s%s/getUpdates" % (config(key='url'), config(key='token'))
message = "%s?" % url
if offset != 0:
message += "offset=%s&" % offset
message += "limit=%s" % limit
try:
result = json.load(urllib.urlopen(message))['result']
except:
result = []
for item in result:
logger.info(msg="Getting updates and returning: %s" % item)
yield item
def clearupdates(offset):
"""
Marks updates as already processed so they are removed by API
:param offset:
:return:
"""
logger = logging.getLogger(__name__)
url = "%s%s/getUpdates" % (config(key='url'), config(key='token'))
message = "%s?" % url
message += "offset=%s&" % offset
try:
result = json.load(urllib.urlopen(message))
except:
result = False
logger.info(msg="Clearing messages")
return result
def updatekarma(word=False, change=0):
"""
Updates karma for a word
:param word: Word to update
:param change: Change in karma
:return:
"""
logger = logging.getLogger(__name__)
value = getkarma(word=word)
return putkarma(word, value + change)
def getkarma(word):
"""
Gets karma for a word
:param word: word to get karma for
:return: karma of given word
"""
logger = logging.getLogger(__name__)
string = (word,)
sql = "SELECT * FROM karma WHERE word='%s';" % string
dbsql(sql)
value = cur.fetchone()
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0
value = 0
return value
def config(key):
"""
Gets configuration from database for a given key
:param key: key to get configuration for
:return: value in database for that key
"""
logger = logging.getLogger(__name__)
string = (key,)
sql = "SELECT * FROM config WHERE key='%s';" % string
dbsql(sql)
value = cur.fetchone()
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0
value = False
return value
def saveconfig(key, value):
"""
Saves configuration for a given key to a defined value
:param key: key to save
:param value: value to store
:return:
"""
logger = logging.getLogger(__name__)
if value:
sql = "UPDATE config SET value = '%s' WHERE key = '%s';" % (value, key)
dbsql(sql)
return value
def createkarma(word):
"""
Creates a new word in karma database
:param word: word to create
:return:
"""
logger = logging.getLogger(__name__)
sql = "INSERT INTO karma VALUES('%s',0);" % word
return dbsql(sql)
def putkarma(word, value):
"""
Updates value of karma for a word
:param word: Word to update
:param value: Value of karma to set
:return:
"""
logger = logging.getLogger(__name__)
if getkarma(word) == 0:
createkarma(word)
if value != 0:
sql = "UPDATE karma SET value = '%s' WHERE word = '%s';" % (value, word)
else:
sql = "DELETE FROM karma WHERE word = '%s';" % word
dbsql(sql)
return value
def getstats(type=False, id=0, name=False, date=False, count=0):
"""
Gets statistics for specified element
:param type: chat or user type to query
:param id: identifier for user or chat
:param name: full name
:param date: date
:param count: number of messages
:return:
"""
logger = logging.getLogger(__name__)
sql = "SELECT * FROM stats WHERE id='%s' AND type='%s';" % (id, type)
dbsql(sql)
try:
value = cur.fetchone()
except:
value = False
if value:
(type, id, name, date, count) = value
if not type or not id or not name or not date:
value = False
if not count:
count = 0
logger.debug(msg="values: type:%s, id:%s, name:%s, date:%s, count:%s" % (type, id, name, date, count))
return value
def getChatMembersCount(chat_id=False):
"""
Get number of users in the actual chat_id
:param chat_id:
:return:
"""
logger = logging.getLogger(__name__)
url = "%s%s/getChatMembersCount?chat_id=%s" % (config(key='url'), config(key='token'), chat_id)
try:
result = str(json.load(urllib.urlopen(url))['result'])
except:
result = 0
logger.info(msg="Chat id %s users %s" % (chat_id, result) )
return result
def updatestats(type=False, id=0, name=False, date=False):
"""
Updates count stats for a given type
:param type: user or chat
:param id: ID to update
:param name: name of the chat of user
:param date: date of the update
:return:
"""
logger = logging.getLogger(__name__)
try:
value = getstats(type=type, id=id)
count = value[4] + 1
except:
value = False
count = 0
type = type
id = id
name = name
if type == "chat":
users = getChatMembersCount(chat_id=id)
else:
users = 0
# Asume value doesn't exist, then set to update if it does
sql = "INSERT INTO stats VALUES('%s', '%s', '%s', '%s', '%s', '%s');" % (type, id, name, date, count, users)
if value:
sql = "UPDATE stats SET type='%s',name='%s',date='%s',count='%s', users='%s' WHERE id='%s';" % (
type, name, date, count, users, id)
logger.debug(msg="values: type:%s, id:%s, name:%s, date:%s, users:%s, count:%s" % (type, id, name, date, users, count))
if id:
try:
dbsql(sql)
except:
print "ERROR on updatestats"
return
def telegramcommands(texto, chat_id, message_id, who_un):
"""
Processes telegram commands in message texts (/help, etc)
:param texto: text from the update
:param chat_id: chat to answer to
:param message_id: message to reply to
:param who_un: username of user providing the command
:return:
"""
logger = logging.getLogger(__name__)
# Process lines for commands in the first word of the line (Telegram)
word = texto.split()[0]
if "@" in word:
# If the message is directed as /help@bot, remove that part
word = word.split("@")[0]
commandtext = False
for case in Switch(word):
if case('/help'):
commandtext = "To use this bot use `word++` or `word--` to increment or decrement karma, a new message will be sent providing the new total\n\n"
commandtext += "Use `rank word` or `rank` to get value for actual word or top 10 rankings\n"
commandtext += "Use `srank word` to search for similar words already ranked\n\n"
commandtext += "Use `/quote add <id> <text>` to add a quote for that username\n"
commandtext += "Use `/quote <id>` to get a random quote from that username\n\n"
if config(key='owner') == who_un:
commandtext += "Use `/quote del <quoteid>` to remove a quote\n\n"
commandtext += "Use `/alias <key>=<value>` to assign an alias for karma\n"
commandtext += "Use `/alias list` to list aliases\n"
commandtext += "Use `/alias delete <key>` to remove an alias\n\n"
commandtext += "Use `/stats <user|chat>` to get stats on last usage\n\n"
commandtext += "Use `/config show` to get a list of defined config settings\n"
commandtext += "Use `/config set <key>=<value>` to define a value for key\n"
commandtext += "Use `/config delete <key>` to delete key\n\n"
commandtext += "Learn more about this bot in [https://github.com/iranzo/stampython](https://github.com/iranzo/stampython)"
break
if case('/start'):
commandtext = "This bot does not use start or stop commands, it automatically checks for karma operands"
break
if case('/stop'):
commandtext = "This bot does not use start or stop commands, it automatically checks for karma operands"
break
if case('/alias'):
aliascommands(texto, chat_id, message_id, who_un)
break
if case('/config'):
configcommands(texto, chat_id, message_id, who_un)
break
if case('/quote'):
quotecommands(texto, chat_id, message_id, who_un)
break
if case('/stats'):
statscommands(texto, chat_id, message_id, who_un)
break
if case():
commandtext = False
# If any of above commands did match, send command
if commandtext:
sendmessage(chat_id=chat_id, text=commandtext, reply_to_message_id=message_id, parse_mode="Markdown")
logger.debug(msg="Command: %s" % word)
return
def getalias(word):
"""
Get alias for a word in case it's defined
:param word: word to search alias
:return: alias if existing or word if not
"""
logger = logging.getLogger(__name__)
string = (word,)
sql = "SELECT * FROM alias WHERE key='%s';" % string
dbsql(sql)
value = cur.fetchone()
logger.debug(msg="getalias: %s" % word)
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0
value = False
# We can define recursive aliases, so this will return the ultimate one
if value:
return getalias(word=value)
return word
def createalias(word, value):
"""
Creates an alias for a word
:param word: word to use as base for the alias
:param value: values to set as alias
:return:
"""
logger = logging.getLogger(__name__)
if getalias(value) == word:
logger.error(msg="createalias: circular reference %s=%s" % (word, value))
else:
if not getalias(word) or getalias(word) == word:
sql = "INSERT INTO alias VALUES('%s','%s');" % (word, value)
logger.debug(msg="createalias: %s=%s" % (word, value))
return dbsql(sql)
return False
def deletealias(word):
"""
Deletes a word from the alias database
:param word: word to delete
:return:
"""
logger = logging.getLogger(__name__)
sql = "DELETE FROM alias WHERE key='%s';" % word
logger.debug(msg="rmalias: %s" % word)
return dbsql(sql)
def listalias(word=False):
"""
Lists the alias defined for a word, or all the aliases
:param word: word to return value for or everything
:return: table with alias stored
"""
logger = logging.getLogger(__name__)
if word:
# if word is provided, return the alias for that word
string = (word,)
sql = "SELECT * FROM alias WHERE key='%s' ORDER by key ASC;" % string
dbsql(sql)
value = cur.fetchone()
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0 value
value = 0
text = "%s has an alias %s" % (word, value)
else:
sql = "select * from alias ORDER BY key ASC;"
dbsql(sql)
text = "Defined aliases:\n"
table = from_db_cursor(cur)
text = "%s\n```%s```" % (text, table.get_string())
logger.debug(msg="Returning aliases %s for word %s" % (text, word))
return text
def setconfig(key, value):
"""
Sets a config parameter in database
:param key: key to update
:param value: value to store
:return:
"""
logger = logging.getLogger(__name__)
if config(key=key):
deleteconfig(key)
sql = "INSERT INTO config VALUES('%s','%s');" % (key, value)
logger.debug(msg="setconfig: %s=%s" % (key, value))
return dbsql(sql)
def deleteconfig(word):
"""
Deletes a config parameter in database
:param word: key to remove
:return:
"""
logger = logging.getLogger(__name__)
sql = "DELETE FROM config WHERE key='%s';" % word
logger.debug(msg="rmconfig: %s" % word)
return dbsql(sql)
def showconfig(key=False):
"""
Shows configuration in database for a key or all values
:param key: key to return value for
:return: Value stored
"""
logger = logging.getLogger(__name__)
if key:
# if word is provided, return the config for that key
string = (key,)
sql = "SELECT * FROM config WHERE key='%s';" % string
dbsql(sql)
value = cur.fetchone()
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0 value
value = 0
text = "%s has a value of %s" % (key, value)
else:
sql = "select * from config ORDER BY key ASC;"
dbsql(sql)
text = "Defined configurations:\n"
table = from_db_cursor(cur)
text = "%s\n```%s```" % (text, table.get_string())
logger.debug(msg="Returning config %s for key %s" % (text, key))
return text
def aliascommands(texto, chat_id, message_id, who_un):
"""
Processes alias commands in the message texts
:param texto: text of the message
:param chat_id: chat_ID
:param message_id: message_ID to reply to
:param who_un: username sending the request
:return:
"""
logger = logging.getLogger(__name__)
logger.debug(msg="Command: %s by %s" % (texto, who_un))
if who_un == config('owner'):
logger.debug(msg="Command: %s by Owner: %s" % (texto, who_un))
try:
command = texto.split(' ')[1]
except:
command = False
try:
word = texto.split(' ')[2]
except:
word = ""
for case in Switch(command):
if case('list'):
text = listalias(word)
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
break
if case('delete'):
key = word
text = "Deleting alias for `%s`" % key
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
deletealias(word=key)
break
if case():
word = texto.split(' ')[1]
if "=" in word:
key = word.split('=')[0]
value = texto.split('=')[1:][0]
text = "Setting alias for `%s` to `%s`" % (key, value)
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id,
disable_web_page_preview=True, parse_mode="Markdown")
# Removing duplicates on karma DB and add the previous values
old = getkarma(key)
updatekarma(word=key, change=-old)
updatekarma(word=value, change=old)
createalias(word=key, value=value)
return
def quotecommands(texto, chat_id, message_id, who_un):
"""
Searches for commands related to quotes
:param texto: text of the message
:param chat_id: chat_ID
:param message_id: message_ID to reply to
:param who_un: username sending the request
:return:
"""
logger = logging.getLogger(__name__)
logger.debug(msg="Command: %s by %s" % (texto, who_un))
# We might be have been given no command, just /quote
try:
command = texto.split(' ')[1]
except:
command = False
for case in Switch(command):
# cur.execute('CREATE TABLE quote(id AUTOINCREMENT, name TEXT, date TEXT, text TEXT;')
if case('add'):
who_quote = texto.split(' ')[2]
date = time.time()
quote = str.join(" ", texto.split(' ')[3:])
result = addquote(username=who_quote, date=date, text=quote)
text = "Quote `%s` added" % result
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
break
if case('del'):
if who_un == config(key='owner'):
id_todel = texto.split(' ')[2]
text = "Deleting quote id `%s`" % id_todel
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id,
disable_web_page_preview=True, parse_mode="Markdown")
deletequote(id=id_todel)
break
if case():
# We're just given the nick (or not), so find quote for it
try:
nick = texto.split(' ')[1]
except:
nick = False
try:
(quoteid, username, date, quote) = getquote(username=nick)
datefor = datetime.datetime.fromtimestamp(float(date)).strftime('%Y-%m-%d %H:%M:%S')
text = '`%s` -- `@%s`, %s (id %s)' % (quote, username, datefor, quoteid)
except:
if nick:
text = "No quote recorded for `%s`" % nick
else:
text = "No quote found"
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
return
def getquote(username=False):
"""
Gets quote for a specified username or a random one
:param username: username to get quote for
:return: text for the quote or empty
"""
logger = logging.getLogger(__name__)
if username:
string = (username,)
sql = "SELECT * FROM quote WHERE username='%s' ORDER BY RANDOM() LIMIT 1;" % string
else:
sql = "SELECT * FROM quote ORDER BY RANDOM() LIMIT 1;"
dbsql(sql)
value = cur.fetchone()
logger.debug(msg="getquote: %s" % username)
try:
# Get value from SQL query
(quoteid, username, date, quote) = value
except:
# Value didn't exist before, return 0
quoteid = False
username = False
date = False
quote = False
if quoteid:
return quoteid, username, date, quote
return False
def addquote(username=False, date=False, text=False):
"""
Adds a quote for a specified username
:param username: username to store quote for
:param date: date when quote was added
:param text: text of the quote
:return: returns quote ID entry in database
"""
logger = logging.getLogger(__name__)
sql = "INSERT INTO quote(username, date, text) VALUES('%s','%s', '%s');" % (username, date, text)
dbsql(sql)
logger.debug(msg="createquote: %s=%s on %s" % (username, text, date))
# Retrieve last id
sql = "select last_insert_rowid();"
dbsql(sql)
lastrowid = cur.fetchone()[0]
return lastrowid
def deletequote(id=False):
"""
Deletes quote from the database
:param id: ID of the quote to remove
:return:
"""
logger = logging.getLogger(__name__)
sql = "DELETE FROM quote WHERE id='%s';" % id
logger.debug(msg="deletequote: %s" % id)
return dbsql(sql)
def configcommands(texto, chat_id, message_id, who_un):
"""
Processes configuration commands in the message
:param texto: text of the message
:param chat_id: chat_id originating the request
:param message_id: message_id to reply to
:param who_un: username of the originator
:return:
"""
logger = logging.getLogger(__name__)
# Only users defined as 'owner' can perform commands
if who_un == config('owner'):
logger.debug(msg="Command: %s by %s" % (texto, who_un))
try:
command = texto.split(' ')[1]
except:
command = False
try:
word = texto.split(' ')[2]
except:
word = ""
for case in Switch(command):
if case('show'):
text = showconfig(word)
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
break
if case('delete'):
key = word
text = "Deleting config for `%s`" % key
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
deleteconfig(word=key)
break
if case('set'):
word = texto.split(' ')[2]
if "=" in word:
key = word.split('=')[0]
value = word.split('=')[1]
setconfig(key=key, value=value)
text = "Setting config for `%s` to `%s`" % (key, value)
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id,
disable_web_page_preview=True, parse_mode="Markdown")
break
if case():
break
return
def showstats(type=False):
"""
Shows stats for defined type or all if missing
:param type: user or chat or empy for combined
:return: table with the results
"""
logger = logging.getLogger(__name__)
if type:
sql = "select * from stats WHERE type='%s' ORDER BY count DESC" % type
else:
sql = "select * from stats ORDER BY count DESC"
dbsql(sql)
table = from_db_cursor(cur)
text = "Defined stats:\n"
text = "%s\n```%s```" % (text, table.get_string())
logger.debug(msg="Returning stats %s" % text)
return text
def statscommands(texto, chat_id, message_id, who_un):
"""
Processes stats commands in the messages
:param texto: message to process
:param chat_id: Chat_ID from the request
:param message_id: message_id to reply to
:param who_un: originating user for the request
:return:
"""
logger = logging.getLogger(__name__)
if who_un == config('owner'):
logger.debug(msg="Owner Stat: %s by %s" % (texto, who_un))
try:
command = texto.split(' ')[1]
except:
command = False
try:
key = texto.split(' ')[2]
except:
key = ""
for case in Switch(command):
if case('show'):
text = showstats(key)
sendmessage(chat_id=chat_id, text=text, reply_to_message_id=message_id, disable_web_page_preview=True,
parse_mode="Markdown")
break
if case():
break
return
def karmacommands(texto, chat_id, message_id):
"""
Finds for commands affecting karma in messages
:param texto: message to analyze
:param chat_id: chat_id originating the request
:param message_id: message_id to reply to
:return:
"""
logger = logging.getLogger(__name__)
# Process lines for commands in the first word of the line (Telegram commands)
word = texto.split()[0]
commandtext = False
# Check first word for commands
for case in Switch(word):
if case('rank'):
try:
word = texto.split()[1]
except:
word = False
commandtext = rank(word)
break
if case('srank'):
try:
word = texto.split()[1]
except:
word = False
commandtext = srank(word)
break
if case():
commandtext = False
# If any of above cases did a match, send command
if commandtext:
sendmessage(chat_id=chat_id, text=commandtext,
reply_to_message_id=message_id, parse_mode="Markdown")
logger.debug(msg="karmacommand: %s" % word)
return
def rank(word=False):
"""
Outputs rank for word or top 10
:param word: word to return rank for
:return:
"""
logger = logging.getLogger(__name__)
if getalias(word):
word = getalias(word)
if word:
# if word is provided, return the rank value for that word
string = (word,)
sql = "SELECT * FROM karma WHERE word='%s';" % string
dbsql(sql)
value = cur.fetchone()
try:
# Get value from SQL query
value = value[1]
except:
# Value didn't exist before, return 0 value