-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
163 lines (135 loc) · 6.21 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
import logging
import os
import sys
import json
import hashlib
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, Handler
import telegram
from telegram import ReplyKeyboardMarkup
from processImg import processImg
InlineKeyboardButton = telegram.InlineKeyboardButton
ENTRY, ENTER_NAME, AWAIT_IMAGE = range(3)
# Enabling logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger()
# Getting mode, so we could define run function for local and Heroku setup
mode = os.getenv("MODE")
TOKEN = os.getenv("TOKEN")
if mode == "dev":
def run(updater):
updater.start_polling()
updater.idle()
elif mode == "prod":
def run(updater):
PORT = int(os.environ.get("PORT", "8443"))
HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
# Code from https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks#heroku
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN))
logger.info("Up and ready to go on heroku!")
else:
logger.error("No MODE specified!")
sys.exit(1)
# open JSON file containing bot commands
with open('commands.json') as f:
data = json.load(f)
def start_handler(update, context):
reply_keyboard = [['Create'],['Cancel']]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
logger.info("Started")
chat_id = update.message.chat_id
logger.info("User {} started bot".format(chat_id))
update.message.reply_text(data['Commands']['Start']['Text'], reply_markup=markup)
return ENTRY
def help_handler(update, context):
# Create a handler-function /help command
commands = data['Commands'].keys()
text = "/start"
update.message.reply_text(data['Commands']['Help']['Text'] + "{}".format(text))
def image_handler(update, context):
file = update.message.photo[-1].get_file()
file.download('img/{}.jpg'.format(file.file_unique_id))
try:
processImg('img/{}.jpg'.format(file.file_unique_id))
context.bot.send_chat_action(chat_id=update.message.chat_id, action="typing")
except Exception:
update.message.reply_text(data['Commands']['photoError']['Text'])
return ENTRY
stickerImg = open("img/r_{}.png".format(file.file_unique_id), 'rb')
# show the user the cropped image
# update.message.reply_photo(stickerImg)
# create/add to sticker pack and return sticker
packname = context.user_data['name']
username = update.message.from_user['username']
hash = hashlib.sha1(bytearray(update.effective_user.id)).hexdigest()
sticker_set_name = "Stitched_{}_by_stichers_bot".format(hash[:10] + packname[:3])
#TODO get emoji from user
context.user_data['sticker-set-name'] = sticker_set_name
logging.info("creating sticker for: userid: {}, stickersetname: {}".format(update.message.from_user.id, sticker_set_name))
try:
context.bot.addStickerToSet(user_id=update.message.from_user.id, name=sticker_set_name, emojis='😄',
png_sticker=open("img/r_{}.png".format(file.file_unique_id), 'rb'))
except Exception:
context.bot.createNewStickerSet(user_id=update.message.from_user.id, name=sticker_set_name,
title=packname, emojis='😄', png_sticker=open("img/r_{}.png".format(file.file_unique_id), 'rb'))
finally:
update.message.reply_text(data['Commands']['nextSticker']['Text'])
stickerImg.close()
os.remove('img/{}.jpg'.format(file.file_unique_id))
os.remove("img/r_{}.png".format(file.file_unique_id))
return AWAIT_IMAGE
def validate_pack_name(name):
return 1 < len(name) < 64
def name_handler(update, context):
pack_name = update.message.text
update.message.reply_text(data['Commands']['nameConfirmation']['Text'] + "{}".format(pack_name))
context.user_data['name'] = pack_name
if validate_pack_name(pack_name):
update.message.reply_text("Name is valid! " + data['Commands']['newPackAddSticker']['Text'])
return AWAIT_IMAGE
else:
update.message.reply_text(data['Commands']['nameError']['Text'])
return ENTER_NAME
def publish_handler(update, context):
update.message.reply_text(data['Commands']['finalizePack']['Text'])
update.message.reply_text(data['Commands']['createPack']['Text'] + "\n https://t.me/addstickers/{}".format(context.user_data['sticker-set-name']))
def cancel(update, context):
update.message.reply_text(data['Commands']['cancel']['Text'])
def check_user_input(update, context):
user_input = update.message.text
logger.info("User input was {}".format(user_input))
if "Create" in user_input:
update.message.reply_text(data['Commands']['namePack']['Text'])
return ENTER_NAME
elif "Cancel" in user_input:
update.message.reply_text(data['Commands']['exit']['Text'])
else:
# ask again
reply_keyboard = [['Create'],['Cancel']]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
update.message.reply_text(
("{}?! ".format(user_input) + data['Commands']['askAgain']['Text']),
reply_markup=markup)
return ENTRY
if __name__ == '__main__':
logger.info("Starting bot")
updater = Updater(TOKEN, use_context=True)
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start_handler)],
states={
ENTRY: [MessageHandler(Filters.text,
check_user_input)],
ENTER_NAME: [MessageHandler(Filters.text,
name_handler, pass_user_data=True)],
AWAIT_IMAGE: [MessageHandler(Filters.photo, image_handler, pass_user_data=True), CommandHandler("publish", publish_handler)],
},
fallbacks=[CommandHandler('cancel', cancel)]
)
dispatcher.add_handler(conv_handler)
dispatcher.add_handler(CommandHandler("start", start_handler))
dispatcher.add_handler(CommandHandler("help", help_handler))
run(updater)