-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
250 lines (207 loc) · 7.91 KB
/
bot.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
import sys
import os
import logging
import uuid
import grapheme
import emoji
from telegram.ext import Updater, InlineQueryHandler, CommandHandler, CallbackContext, ChatMemberHandler, MessageHandler, Filters
from telegram import Update, InlineQueryResultCachedSticker
from dotenv import load_dotenv
import saysdb
from saysdb import with_connection
from cendynebreaths import CendyneBreathes
from cendynesmol import CendyneSmol
from cendynesays import CendyneSays
import stickers
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
load_dotenv()
say = CendyneSays()
smol = CendyneSmol()
breathes = CendyneBreathes()
token = os.environ["BOT_TOKEN"]
if os.getenv("USE_GLEAM") is not None:
if os.getenv("GLEAM_TOKEN") is not None:
token = os.environ["GLEAM_TOKEN"]
else:
print("GLEAM_TOKEN expected..")
log_chan = int(os.getenv("LOG_CHAN"))
def makeSticker(text):
if text == "":
text = "Message Here"
keep = False
oldtext = text
try:
text = emoji.demojize(text, use_aliases=True)
# print(text)
text = emoji.emojize(text, use_aliases=True)
# print(text.encode("raw_unicode_escape").decode("latin_1"))
except Exception as ex:
# print(ex)
logging.exception("Error during emoji")
if len(text) > 120:
text = "UwU Desu: Your message was too long"
# print("text ", text)
if text != oldtext:
logging.info("Text converted to %s", text)
reverse = False
if text.startswith("reverse:"):
reverse = True
text = text[8:].strip()
elements = list(grapheme.graphemes(text))
try:
le = len(elements)
if le <= 4:
if le == 3 and elements[0] == elements[1] and elements[1] == elements[2]:
counts = [40, 30, 20, 10, 5, 4, 3, 2, 1, 0]
if reverse:
counts = [10, 8, 5, 4, 3, 2, 1, 0]
for count in counts:
if count == 0:
sticker = say.makeSticker("Unsupported :(")
break
sticker = breathes.makeSticker(text, count, reverse)
if not stickers.validSize(sticker):
# Try a smaller particle size until the file is
# within Telegram's requirement
# print("Count ", count, " resulted in too large of a file")
logging.info(
"Count %d result in too large of a file", count)
continue
break
elif os.getenv("USE_GLEAM") is not None:
sticker = say.makeSticker(text)
else:
act = None
if elements[le - 1] == "!":
act = smol.actExclaim
elif elements[le - 1] == "?":
act = smol.actQuestion
elif le == 1:
act = smol.actNormal
if act is not None:
# print("Smol sticker ", text)
logging.info("Smol sticker %s", text)
sticker = smol.makeSticker(text, act)
else:
# Fallback to the normal text thing
sticker = say.makeSticker(text)
else:
sticker = say.makeSticker(text)
except Exception as ex:
# print("Exception ex", ex)
# traceback.print_exception(*sys.exc_info())
logging.exception("An error %s", ex)
text = ".-. An error"
keep = True
sticker = say.makeSticker(text)
if not stickers.validSize(sticker):
stickers.deleteSticker(sticker)
text = "OwO Desu: The sticker was too big for Telegram"
keep = True
sticker = say.makeSticker(text)
return sticker, keep
@with_connection
def start(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
# print(update)
logging.info("Start issued")
update.message.reply_text(
'Use @CendyneSaysBot text here to make a message')
@with_connection
def messageHandler(update: Update, c: CallbackContext) -> None:
# print("Message handler!!!", update)
logging.info("Incoming message %s", update)
try:
if update.message:
text = update.message.text
if saysdb.isTombstoned(update.message.text):
update.message.reply_text("An error")
return
cached = saysdb.cachedText(update.message.text)
if cached:
logging.info("Using cached result")
update.message.reply_document(document=cached)
return
sticker, keep = makeSticker(text)
# print("About to reply with document ", sticker)
logging.info("About to reply with sticker %s", sticker)
# result = update.message.reply_document(document=open(sticker, "rb"))
result = c.bot.send_document(
chat_id=log_chan, document=open(sticker, "rb"))
update.message.reply_document(document=result.sticker.file_id)
saysdb.cacheText(update.message.text, result.sticker.file_id)
# print("Result:", result)
logging.info("Sent sticker result %s", str(result))
if not keep:
stickers.deleteSticker(sticker)
except Exception as ex:
# print("A problem I guess")
# traceback.print_exception(*sys.exc_info())
logging.exception("A problem I guess, %s", ex)
saysdb.tombstone(update.message.text)
@with_connection
def inlinequery(update: Update, c: CallbackContext) -> None:
"""Handle the inline query."""
query = update.inline_query.query
keep = False
if query == "":
return
# print(update)
# print(update.inline_query.from_user)
logging.info("Inline query %s", str(update))
if saysdb.isTombstoned(query):
update.inline_query.answer([])
return
cached = saysdb.cachedText(query)
if cached:
logging.info("Using cached result")
results = [
InlineQueryResultCachedSticker(
id=uuid.uuid4(),
sticker_file_id=cached,
),
]
update.inline_query.answer(results)
return
try:
sticker, keep = makeSticker(query)
result = c.bot.send_document(
chat_id=log_chan, document=open(sticker, "rb"))
saysdb.cacheText(query, result.sticker.file_id)
results = [
InlineQueryResultCachedSticker(
id=uuid.uuid4(),
sticker_file_id=result.sticker.file_id,
),
]
update.inline_query.answer(results)
if not keep:
stickers.deleteSticker(sticker)
except Exception as ex:
# print("A problem I guess")
# traceback.print_exception(*sys.exc_info())
logging.exception("A problem I guess")
saysdb.tombstone(query)
def main() -> None:
saysdb.init()
# Create the Updater and pass it your bot's token.
updater = Updater(token)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
# on non command i.e message - echo the message on Telegram
dispatcher.add_handler(InlineQueryHandler(inlinequery))
dispatcher.add_handler(ChatMemberHandler(messageHandler))
dispatcher.add_handler(MessageHandler(Filters.text, messageHandler))
me = updater.bot.get_me()
print("Bot: ", me)
# Start the Bot
updater.start_polling()
# Block until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()