Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import flask
- from flask_sqlalchemy import SQLAlchemy
- import telebot
- import logging
- import dice
- import rpg
- logger = telebot.logger
- telebot.logger.setLevel(logging.DEBUG)
- API_TOKEN = '305501408:AAHWH_mzAcSFr9fER2oqupn_UD4ymjaNaIQ'
- WEBHOOK_URL_BASE = 'https://sahdoum.pythonanywhere.com'
- WEBHOOK_URL_PATH = '/%s/' % API_TOKEN
- bot = telebot.TeleBot(API_TOKEN, threaded=False)
- app = flask.Flask(__name__)
- SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
- username="sahdoum",
- password="aaaaaaaa8",
- hostname="sahdoum.mysql.pythonanywhere-services.com",
- databasename="sahdoum$FATAL",
- )
- app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
- app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
- app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
- db = SQLAlchemy(app)
- class User(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- chat_id = db.Column(db.Integer, unique=True)
- chat_name = db.Column(db.String(80), unique=True)
- location = db.Column(db.String(256), unique=True)
- def __init__(self, chat_id, chat_name, location):
- self.chat_id = chat_id
- self.name = name
- self.location = location
- def __repr__(self):
- return '<User %r>' % self.name
- @app.route('/')
- def index():
- return 'Hello!'
- @app.route(WEBHOOK_URL_PATH, methods=['POST'])
- def webhook():
- if flask.request.headers.get('content-type') == 'application/json':
- json_string = flask.request.get_data().decode('utf-8')
- update = telebot.types.Update.de_json(json_string)
- bot.process_new_updates([update])
- return ''
- else:
- flask.abort(403)
- text_messages = {
- 'help':
- u'Во многой мудрости много печали; и кто умножает познания, умножает скорбь.\n'
- u'Но ищущему знания я поведаю свои команды:\n'
- u'/help - информация о боте\n'
- u'/roll - броски дайсов\n'
- u'/r - короткая команда для /roll\n'
- u'/rf - бросок в FATE\n'
- u'/rg - бросок в GURPS\n'
- u'/fatal - используй команду эту с большой осторожностью\n'
- }
- # ---- ----
- # ---- Start methods ----
- # Handle '/start'
- @bot.message_handler(commands=['start'])
- def send_welcome(message):
- bot.reply_to(message, "Bot enabled")
- # Handle '/stop'
- @bot.message_handler(commands=['stop'])
- def send_stop(message):
- bot.reply_to(message, "Bot disabled")
- # Handle '/help'
- @bot.message_handler(commands=['help'])
- def help (message):
- bot.reply_to(message, text_messages['help'])
- # Handle 'new_chat_participant'
- @bot.message_handler(func=lambda m: True, content_types=['new_chat_participant'])
- def greeting(message):
- bot.reply_to(message, "Приветствую, путник!")
- # Handle '/add'
- @bot.message_handler(commands=['add'])
- def help (message):
- usr = User(message.chat.id, u"Диса "+message.chat.id, "start") #message.from.first_name
- db.session.add(usr)
- db.session.commit()
- bot.reply_to(message, u"Добавлено")
- # Handle '/list'
- @bot.message_handler(commands=['list'])
- def help (message):
- usr_list = User.query.all()
- msg = u"Набор пидоров: \n"
- for usr in usr_list:
- msg += usr.name+'\n'
- bot.reply_to(message, msg)
- # Handle '/del'
- @bot.message_handler(commands=['del'])
- def help (message):
- User.query.delete()
- bot.reply_to(message, u"Удалено")
- # ---- ----
- # ---- Different rolls ----
- # Handle '/roll' 'r'
- @bot.message_handler(commands=['roll', 'r'])
- def roll (message):
- arg = message.text.split(' ')
- if len(arg)>1:
- try:
- result = dice.roll(arg[1])
- bot.reply_to(message, "Вы выкинули:\n"+str(result))
- except:
- bot.reply_to(message, "Неправильное выражение.")
- else:
- bot.reply_to(message, u'Вжух:\n'+str(dice.roll('4d6')))
- # Handle '/rf'
- @bot.message_handler(commands=['rf'])
- def rollFate (message):
- roll = dice.roll('4d3')
- result = 0
- text = u"Вы выкинули:\n"
- for i in roll:
- if i == 1:
- text += "[-]"
- elif i == 2:
- text += "[0]"
- else:
- text += "[+]"
- result += i-2
- arg = message.text.split(' ')
- if len(arg)>1:
- text += "+"+arg[1]
- result += int(arg[1])
- text += '=\n{0}'.format(result)
- bot.reply_to(message, text)
- # Handle '/rg'
- @bot.message_handler(commands=['rg'])
- def rollGURPS(message):
- arg = message.text.split(' ')
- roll = dice.roll('3d6t')
- text = str(roll)
- if len(arg)>1:
- if roll > int(arg[1]):
- text += " > "+arg[1]+u"\nПровал"
- else:
- text += " ≤ "+arg[1]+u"\nУспех"
- bot.reply_to(message, text)
- # ---- ----
- # ---- Image parasha ----
- # Handle '/image'
- @bot.message_handler(commands=['image'])
- def send_image(message):
- logger.debug('Sending image')
- img = Image.new('RGB', (512, 512))
- base = random.randint(0, 16777216)
- pixels = [base + i * j for i in range(512) for j in range(512)] # generate sample image
- img.putdata(pixels)
- img.save('temp.jpg', 'JPEG')
- bot.send_photo(message.chat.id, open('temp.jpg', 'rb'))
- @bot.message_handler(commands=['image2'])
- def send_image2(message):
- logger.debug('Sending photo!')
- bot.send_photo(message.chat.id, open('test.jpg', 'rb'))
- # ---- ----
- # ---- FATAL ----
- fatal_editor = rpg.Editor('fatal')
- # Handle /fatal
- @bot.message_handler(commands=['fatal'])
- def fatal_message(message):
- try:
- fatal = rpg.Game('fatal', 'fatal_messages', message.chat.id, 'users')
- dsc = fatal.generate_location()
- btn = dsc['buttons']
- bot.reply_to(message, dsc['text'], parse_mode='Markdown', reply_markup=btn)
- if btn:
- bot.register_next_step_handler(message, next_fatal)
- except Exception as e:
- bot.reply_to(message, 'Exception: '+str(e))
- # Handle next message after /fatal
- def next_fatal(message):
- try:
- fatal = rpg.Game('fatal', 'fatal_messages', message.chat.id, 'users')
- dsc = fatal.generate_location(message.text)
- btn = dsc['buttons']
- bot.reply_to(message, dsc['text'], parse_mode='Markdown', reply_markup=btn)
- if btn:
- bot.register_next_step_handler(message, next_fatal)
- except Exception as e:
- bot.reply_to(message, 'Exception: '+str(e))
- # Handle /addfatal
- @bot.message_handler(commands=['addfatal'])
- def add_fatal_msg(message):
- if ' ' in message.text:
- fatal_editor.tmp_loc_key = message.text.split(' ', maxsplit=1)[1]
- else:
- fatal_editor.tmp_loc_key = 'fatal_messages'
- bot.reply_to(message, u"Напишите запись:")
- bot.register_next_step_handler(message, request_new_fatal_msg)
- # Handle new msg description
- def request_new_fatal_msg(message):
- text = message.text
- fatal_editor.tmp_loc_dsc = text
- bot.send_message(message.chat.id, u"Сообщение записано. Напишите сообщение для кнопки или завершите командой /done")
- bot.register_next_step_handler(message, request_button)
- # Handle button description or /done command
- def request_button(message):
- if message.text == '/done':
- fatal_editor.set_location(message.chat.id)
- bot.send_message(message.chat.id, u"Запись добавлена!")
- else:
- fatal_editor.tmp_loc_btn_dsc = message.text
- bot.send_message(message.chat.id, u"Напишите файл сообщений для кнопки.")
- bot.register_next_step_handler(message, request_buttonlink)
- # Handle button link
- def request_buttonlink(message):
- fatal_editor.tmp_loc_btn[fatal_button_key] = message.text
- bot.send_message(message.chat.id, u"Кнопка добавлена. Напишите сообщение еще для одной кнопки или завершите командой /done")
- bot.register_next_step_handler(message, request_button)
- # Handle /delfatal
- @bot.message_handler(commands=['delfatal'])
- def delete_fatal_message(message):
- #так вообще без объявления можно?
- if ' ' in message.text:
- key = message.text.split(' ', maxsplit=1)[1]
- else:
- key = 'fatal_messages'
- msg_gen = fatal_editor.delete_list_generator(message.id, key, 'fatal_delete')
- for m in msg_gen:
- bot.send_message(message.chat.id, m['text'], parse_mode='Markdown', reply_markup=m['buttons'])
- # Handle callback for fatal delete
- @bot.callback_query_handler(func=lambda call: call.data.split(' ')[0] == 'fatal_delete')
- def callback_inline(call):
- if call.message:
- index = int(call.data.split(' ')[1])
- fatal_editor.delete(call.message.chat.id, index)
- bot.send_message(chat_id, u"Сообщение удалено.")
- # ---- ----
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement