Channel-Poll-Bot/bot.py

61 lines
1.8 KiB
Python
Raw Normal View History

2019-01-01 17:19:23 +01:00
#!/usr/bin/env python3
# coding=utf-8
2019-01-06 18:52:34 +01:00
import logging
2019-01-01 17:19:23 +01:00
import config
import sqlite3
from telegram.ext import Updater, MessageHandler, Filters
2019-01-06 18:52:34 +01:00
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
2019-01-01 17:19:23 +01:00
2019-01-06 18:52:34 +01:00
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - \
%(message)s', level=logging.INFO)
2019-01-01 17:19:23 +01:00
2019-01-06 18:52:34 +01:00
def get_callback_id(db):
cursor = db.cursor()
query = ('SELECT max(callback) FROM poll')
cursor.execute(query)
return int(cursor.fetchone()[0]) + 1
2019-01-06 19:02:29 +01:00
def add_vote(db, callback_id, user=None):
if user is not None:
user_id = user.id
name = str(user.first_name)
if user.last_name:
name += " " + str(user.last_name)
else:
user_id = 0
name = ""
2019-01-06 18:52:34 +01:00
cursor = db.cursor()
2019-01-06 19:02:29 +01:00
query = ("INSERT INTO poll(callback, user_id, name) values(?,?,?)")
cursor.execute(query, (callback_id, user_id, name))
2019-01-06 18:52:34 +01:00
db.commit()
def post(bot, update, db):
2019-01-01 17:19:23 +01:00
chat_id = update.message.chat_id
if chat_id in config.allowed_users:
2019-01-06 18:52:34 +01:00
callback_id = get_callback_id(db)
2019-01-06 19:02:29 +01:00
add_vote(db, callback_id)
2019-01-06 18:52:34 +01:00
photo = update.message.photo[0]
file_id = photo.file_id
keyboard = InlineKeyboardMarkup([[InlineKeyboardButton(text="❤️",
callback_data=callback_id)]])
bot.send_photo(chat_id=config.channel_id, photo=file_id,
reply_markup=keyboard)
2019-01-01 17:19:23 +01:00
else:
bot.send_message(chat_id=chat_id, text="Not Authorized")
updater = Updater(token=config.api_key)
dispatcher = updater.dispatcher
db = sqlite3.connect("chanbot.sqlite", check_same_thread=False)
cursor = db.cursor()
2019-01-06 18:52:34 +01:00
dispatcher.add_handler(MessageHandler(Filters.photo, lambda x, y: post(x,
2019-01-01 17:19:23 +01:00
y, db)))
updater.start_polling()