def self_kick_callback(bot, message): """ if bot gets kicked it erases all data for chat """ cid = get_cid(message) with db: chat = Chats.select().where(Chats.cid == cid) if chat.exists(): chat = chat.get() invited_by = chat.invited_by chat.delete_instance() tacos = Tacos.select().where(Tacos.chat == cid) if tacos.exists(): tacos.get().delete_instance() chat_title = message.chat.title try: bot.send_message(invited_by, data_deleted_phrase.format(chat_title), parse_mode='html') except Exception as e: """ user blocked the bot """ print(e)
def taco_mention_callback(bot, message): """ callback for taco-transfer by mention """ cid = get_cid(message) store_name(message) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, message, bot) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) mentioned_users = list() for entity in message.entities: if entity.type == 'mention': user = message.text[entity.offset: entity.offset + entity.length].lower() mentioned_users.append(user) mentioned_users = list(set(mentioned_users)) # removing duplicates if len(mentioned_users) > 1: if chat.less is True: text = only_one_receiver_phrase.split('\n')[0] else: text = only_one_receiver_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() return sender = message.from_user receiver_username: str = ensure_no_at_sign(mentioned_users[0]) try: receiver = bot.get_chat_member(chat_id=cid, user_id=receiver_username).user except Exception: """ here should be except UserNotParticipant, but it still raises this exception """ if chat.less is True: text = user_not_present_phrase.split('\n')[0] else: text = user_not_present_phrase mid = bot.send_message(chat_id=cid, text=text.format(ensure_username(receiver_username)), reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() return give_tacos(bot, message, sender, receiver)
def my_tacos_callback(bot, message): """ shows users taco-balance """ cid = get_cid(message) uid = str(get_uid(message)) with db: chat = Chats.get(Chats.cid == message.chat.id) tacos = Tacos.get(Tacos.chat == cid) balances = tacos.taco_balance delete_message(bot, message) user_name = store_name(message.from_user) if uid in balances.keys(): balance = balances.get(uid) else: balances.update({uid: default_taco_amount}) tacos.taco_balance = balances tacos.save() balance = default_taco_amount if chat.less is True: comment = '' else: if balance < 25: comment = balance_comment_low elif balance > 60: comment = balance_comment_high else: comment = balance_comment_medium if chat.autohide: msg = bot.send_message(chat_id=cid, text=balance_phrase.format(user_name, balance, comment), reply_to_message_id=get_mid(message), parse_mode='html') time = datetime.datetime.now() + datetime.timedelta(minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) msg = bot.send_message(chat_id=cid, text=balance_phrase.format(user_name, balance, comment), reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html') chat.mids = [msg.message_id] chat.save()
def taco_top_callback(bot, message): """ shows top-5(or less) taco-users in chat """ cid = get_cid(message) mid = get_mid(message) store_name(message) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, message, bot) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format( message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) tacos = Tacos.get(Tacos.chat == cid) balances = json.loads(tacos.taco_balance) if len(balances) == 0: # in case tacos-table is empty bot.send_message(text=empty_top_phrase, chat_id=cid, reply_to_message_id=mid, reply_markup=ok_keyboard, parse_mode='html') return top = list() while len(balances) > 0 and len(top) < 5: top_uid = max(balances, key=balances.get) username = resolve_name(top_uid) top.append([username, balances.get(top_uid)]) del balances[top_uid] formatted_top = '' for user in top: if "@" in user[0]: user_link = "https://t.me/{}".format(user[0][1:]) else: user_link = "tg://user?id={}".format(user[0]) formatted_top += '{}. <a href="{}">{}</a> - <code>{}</code> tacos!\n'.format( top.index(user) + 1, user_link, user[0][1:], user[1]) mid = bot.send_message(text=taco_top_phrase.format(len(top), formatted_top), chat_id=cid, reply_to_message_id=mid, reply_markup=ok_keyboard, parse_mode='html', disable_web_page_preview=True).message_id chat.mids = json.dumps([mid]) chat.save()
def query_callback(update: Update, context: callbackcontext): """ search query callback (private chat only) """ cid = get_cid(update) q = update.message.text clean_chat(update, context) store_user(update) message_id = context.bot.send_message(chat_id=cid, text=searching_phrase, parse_mode=ParseMode.HTML).message_id results = parse_html(get_html(add_url(format_query(q)))) if len(results) == 0: context.bot.edit_message_text(chat_id=cid, message_id=message_id, text=no_results_phrase, parse_mode=ParseMode.HTML) context.chat_data.update({'message_ids': [message_id]}) return context.chat_data.update({'results': results}) download_button = InlineKeyboardButton(text=download_button_text, callback_data='download:0') if len(results) > 1: next_button = InlineKeyboardButton(text=next_button_text, callback_data='track:1') keyboard = InlineKeyboardMarkup([[download_button], [next_button]]) else: keyboard = InlineKeyboardMarkup([[download_button]]) context.bot.edit_message_text(chat_id=cid, message_id=message_id, text=track_form.format(1, len(results), results[0]['performer'], results[0]['title'], results[0]['duration']), parse_mode=ParseMode.HTML, reply_markup=keyboard) context.chat_data.update({'message_ids': [message_id]})
def new_chat_callback(bot, message): """ triggers when bot gets added to new chat """ cid = get_cid(message) store_name(message) invited_by = message.from_user Chats.create(cid=cid, invited_by=invited_by.id) Tacos.create(chat=cid) bot.send_message(cid, chat_enabled_phrase, parse_mode='html')
def switch_track_callback(update: Update, context: callbackcontext): cid = get_cid(update) mid = update.callback_query.message.message_id next_track = int(update.callback_query.data.split(':')[-1]) if context.chat_data.get('results') is None: context.bot.delete_message(chat_id=cid, message_id=mid) return results = context.chat_data['results'] download_button = InlineKeyboardButton(text=download_button_text, callback_data='download:{}'.format(next_track)) next_button = InlineKeyboardButton(text=next_button_text, callback_data='track:{}'.format(next_track + 1)) previous_button = InlineKeyboardButton(text=previous_button_text, callback_data='track:{}'.format(next_track - 1)) if next_track == len(results) - 1: keyboard = InlineKeyboardMarkup([[download_button], [previous_button]]) elif next_track == 0: keyboard = InlineKeyboardMarkup([[download_button], [next_button]]) else: keyboard = InlineKeyboardMarkup([[download_button], [previous_button, next_button]]) try: context.bot.edit_message_text(chat_id=cid, message_id=mid, text=track_form.format(next_track + 1, len(results), results[next_track]['performer'], results[next_track]['title'], results[next_track]['duration']), parse_mode=ParseMode.HTML, reply_markup=keyboard) except BadRequest: pass
def my_tacos_callback(bot, message): """ shows users taco-balance """ cid = get_cid(message) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, message, bot) store_name(message) uid = str(get_uid(message)) tacos = Tacos.get(Tacos.chat == cid) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format( message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) balances = json.loads(tacos.taco_balance) if uid in balances.keys(): balance = balances.get(uid) else: balances.update({uid: default_taco_amount}) tacos.taco_balance = json.dumps(balances) tacos.save() balance = default_taco_amount if chat.less is True: comment = '' else: if balance < 25: comment = balance_comment_low elif balance > 60: comment = balance_comment_high else: comment = balance_comment_medium mid = bot.send_message(chat_id=cid, text=balance_phrase.format(balance, comment), reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save()
def new_chat_callback(bot, message): """ triggers when bot gets added to new chat """ cid = get_cid(message) if message.from_user is not None: store_name(message.from_user) invited_by = message.from_user if invited_by is None: invited_by = -1 else: invited_by = invited_by.id with db: Chats.create(cid=cid, invited_by=invited_by) Tacos.create(chat=cid) bot.send_message(cid, chat_enabled_phrase, parse_mode='html')
def give_tacos(bot, message, sender, receiver): cid = get_cid(message) tacos = Tacos.get(Tacos.chat == cid) chat = Chats.get(Chats.cid == message.chat.id) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format( message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) sender_name = store_name(sender) receiver_name = store_name(receiver) if receiver.is_bot: if chat.less is True: text = no_bots_allowed_phrase.split('\n')[0] else: text = no_bots_allowed_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = [mid] chat.save() return sender_id = str(sender.id) receiver_id = str(receiver.id) if sender_id == receiver_id: if chat.less is True: text = self_tacoing_phrase.split('\n')[0] else: text = self_tacoing_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html').message_id chat.mids = [mid] chat.save() return tacos_sent = len(re.findall(taco_emoji, message.text)) txt = message.text if message.entities is not None: for entity in message.entities: txt = txt[:entity.offset] + txt[entity.offset + entity.length:] txt = txt.replace(taco_emoji, '') user_comment = txt.lstrip(' ') if tacos.taco_balance is None: amounts = dict() amounts.update({sender_id: default_taco_amount}) amounts.update({receiver_id: default_taco_amount}) else: amounts = tacos.taco_balance if sender_id not in amounts.keys(): amounts.update({sender_id: default_taco_amount}) if receiver_id not in amounts.keys(): amounts.update({receiver_id: default_taco_amount}) if tacos_sent > amounts.get(sender_id): if chat.less is True: text = balance_low_phrase.split('\n')[0] else: text = balance_low_phrase if chat.autohide: msg = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html') time = datetime.datetime.now() + datetime.timedelta( minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: msg = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html') chat.mids = [msg.message_id] chat.save() return amounts.update({sender_id: amounts.get(sender_id) - tacos_sent}) amounts.update({receiver_id: amounts.get(receiver_id) + tacos_sent}) if chat.less is True: comment = '' else: if tacos_sent < 3: comment = taco_transfer_comment_low elif tacos_sent > 9: comment = taco_transfer_comment_high else: comment = taco_transfer_comment_medium.format(receiver_name) if "@" in sender_name: sender_link = "https://t.me/{}".format(sender_name[1:]) else: sender_link = "tg://user?id={}".format(sender_id) if "@" in receiver_name: receiver_link = "https://t.me/{}".format(receiver_name[1:]) else: receiver_link = "tg://user?id={}".format(receiver_id) if tacos_sent == 1: phrase = taco_transfer_phrase.replace('tacos', 'taco') else: phrase = taco_transfer_phrase if len(user_comment) > 0: phrase += '<b>And said:</b>\n>>><code>{}</code>'.format(user_comment) if chat.autohide: msg = bot.send_message(chat_id=cid, text=phrase.format(sender_link, sender_name, tacos_sent, receiver_link, receiver_name, comment), parse_mode='html', disable_web_page_preview=True) time = datetime.datetime.now() + datetime.timedelta( minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: msg = bot.send_message(chat_id=cid, text=phrase.format(sender_link, sender_name, tacos_sent, receiver_link, receiver_name, comment), reply_markup=ok_keyboard, parse_mode='html', disable_web_page_preview=True) chat.mids = [msg.message_id] chat.save() tacos.taco_balance = amounts tacos.save()
def download_track_callback(update: Update, context: callbackcontext): cid = get_cid(update) mid = update.callback_query.message.message_id if context.chat_data.get('results') is None: context.bot.delete_message(chat_id=cid, message_id=mid) return try: context.bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=download_started_phrase) except BadRequest: # user spams bot with downloads pass song_index = int(update.callback_query.data.split(':')[-1]) song = context.chat_data['results'][song_index] download_url = song['download_url'] performer = song['performer'] title = song['title'] r = requests.get(download_url, stream=True) file_name = (performer + '-' + title + str(randint(0, 9999)) + '.mp3').replace('/', ' ') with open(file_name, 'bw') as file: for chunk in r.iter_content(2048): file.write(chunk) path = os.path.abspath(file_name) size = ((os.path.getsize(path)) / 1024) / 1024 size = round(size, 2) if size > 50: os.remove(path) try: context.bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=file_too_large_phrase) except BadRequest: pass return file_id = 0 audio = open(path, 'rb') for i in range(5): try: message = context.bot.send_audio(chat_id=cid, performer=performer, title=title, audio=audio, timeout=1000) file_id = message.audio.file_id except BadRequest: # this is the only way to make sure the file was sent continue break audio.close() os.remove(path) if file_id == 0: try: context.bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=error_occurred_phrase) except BadRequest: # callback_query is too old pass store_track(uid=cid, title=title, performer=performer, file_id=file_id, download_url=download_url)
def give_tacos(bot, message, sender, receiver): cid = get_cid(message) tacos = Tacos.get(Tacos.chat == cid) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, message, bot) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) if receiver.username is None: first_name = receiver.first_name last_name = receiver.last_name if last_name is None: receiver_name = first_name else: receiver_name = first_name + " " + last_name else: receiver_name = "@" + receiver.username if receiver.is_bot: # no tacos for bots if chat.less is True: text = no_bots_allowed_phrase.split('\n')[0] else: text = no_bots_allowed_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), reply_markup=ok_keyboard, parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() return sender_id = str(sender.id) receiver_id = str(receiver.id) if sender_id == receiver_id: # self-tacoing is forbidden if chat.less is True: text = self_tacoing_phrase.split('\n')[0] else: text = self_tacoing_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() return tacos_sent = len( re.findall(taco_emoji, message.text) ) if tacos.taco_balance is None: # initialising/restoring user-balances amounts = dict() amounts.update({sender_id: default_taco_amount}) amounts.update({receiver_id: default_taco_amount}) else: amounts = json.loads(tacos.taco_balance) if sender_id not in amounts.keys(): amounts.update({sender_id: default_taco_amount}) if receiver_id not in amounts.keys(): amounts.update({receiver_id: default_taco_amount}) if tacos_sent > amounts.get(sender_id): # can't send more than you have if chat.less is True: text = balance_low_phrase.split('\n')[0] else: text = balance_low_phrase mid = bot.send_message(chat_id=cid, text=text, reply_to_message_id=get_mid(message), parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() return amounts.update( {sender_id: amounts.get(sender_id) - tacos_sent} ) amounts.update({receiver_id: amounts.get(receiver_id) + tacos_sent}) if chat.less is True: comment = '' else: if tacos_sent < 3: comment = taco_transfer_comment_low elif tacos_sent > 9: comment = taco_transfer_comment_high else: comment = taco_transfer_comment_medium.format(receiver_name) mid = bot.send_message(chat_id=cid, text=taco_transfer_phrase.format(tacos_sent, receiver_name, comment), reply_markup=ok_keyboard, reply_to_message_id=get_mid(message), parse_mode='html').message_id chat.mids = json.dumps([mid]) chat.save() tacos.taco_balance = json.dumps(amounts) # saving data tacos.save()
def filter_new_chat_(_, query): # filter for group, that has tacos-field in DB with db: return Chats.select().where(Chats.cid == get_cid(query)).exists()
def taco_top_callback(bot, message): """ shows top-5(or less) taco-users in chat """ cid = get_cid(message) mid = get_mid(message) store_name(message.from_user) chat = Chats.get(Chats.cid == message.chat.id) clean_chat(chat.mids, chat.cid, bot, message) ok_button = InlineKeyboardButton('OK', callback_data='delete:{}'.format(message.from_user.id)) ok_keyboard = InlineKeyboardMarkup([[ok_button]]) tacos = Tacos.get(Tacos.chat == cid) balances = tacos.taco_balance if len(balances) == 0: if chat.autohide: msg = bot.send_message(text=empty_top_phrase, chat_id=cid, parse_mode='html') time = datetime.datetime.now() + datetime.timedelta(minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: bot.send_message(text=empty_top_phrase, chat_id=cid, reply_markup=ok_keyboard, parse_mode='html') return top = list() while len(balances) > 0 and len(top) < 5: top_uid = max(balances, key=balances.get) username = resolve_name(top_uid) top.append([username, balances.get(top_uid)]) del balances[top_uid] formatted_top = '' for user in top: if "@" in user[0]: user_link = "https://t.me/{}".format(user[0][1:]) else: user_link = "tg://user?id={}".format(user[0]) formatted_top += '{}. <a href="{}">{}</a> - <code>{}</code> tacos!\n'.format(top.index(user) + 1, user_link, user[0][1:], user[1]) if chat.autohide: msg = bot.send_message(text=taco_top_phrase.format(len(top), formatted_top), chat_id=cid, parse_mode='html', disable_web_page_preview=True) time = datetime.datetime.now() + datetime.timedelta(minutes=chat.autohide_delay) sched.add_job(delete_message, 'date', run_date=time, args=[bot, msg]) else: bot.send_message(text=taco_top_phrase.format(len(top), formatted_top), chat_id=cid, reply_markup=ok_keyboard, parse_mode='html', disable_web_page_preview=True) chat.mids.append(mid) chat.save()