|
| 1 | +# -*- coding: utf8 -*- |
| 2 | +#/usr/bin/python3.7 |
| 3 | + |
| 4 | +import datetime |
| 5 | +from telegram import bot |
| 6 | +from telegram.ext import Updater, Filters, MessageHandler, CallbackQueryHandler |
| 7 | +from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ParseMode |
| 8 | +import os |
| 9 | +import codecs |
| 10 | + |
| 11 | +# https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0 |
| 12 | +bot_token = 'TOKEN' |
| 13 | +bot_id = None |
| 14 | + |
| 15 | +#bot will delete his owm nessage after defined time |
| 16 | +destruction_timeout = 20 |
| 17 | + |
| 18 | +database_filename = 'users.txt' |
| 19 | + |
| 20 | +stopwords = ["залупа","суха","сиха","сри","срали","срать","д@ун", "даун","хуи","хуё","хуе","хуй", "бля","Cyка", "nahui","говн","pizd","pidar","cunt","Пизд","хер","Пидарас","Пидор","Бляд","Блят","Гандон","Выеби","Еби","Блядство","Выебон","Выебать","Вхуюжить","Гомосек","Долбоёб","Далбоёб","Ебло","Еблище","Ебать","Ебическая сила","Ебунок","Еблан","Ёбнуть","Ёболызнуть","Ебош","Заебал","Заебатый","Злаебучий","Заёб","Иди на хуй","Колдоебина","Манда","Мандовошка","Мокрощелка","Наебка","Наебал","Наебаловка","Напиздеть","Отъебись","Охуеть","Отхуевертить","Опизденеть","Охуевший","Отебукать","Пизда","Пидарас","Пиздатый","Пиздец","Пизданутый","Поебать","Поебустика","Проебать","Подзалупный","Пизденыш","Припиздак","Разъебать","Распиздяй","Разъебанный","Сука","Сучка","Трахать","Уебок","Уебать","Угондошить","Уебан","Хитровыебанный","Хуй","Хуйня","Хуета","Хуево","Хуесос","Хуеть","Хуевертить","Хуеглот","Хуистика","Членосос","Членоплет","Шлюха"] |
| 21 | +increase_words = ['+','спасибо','дякую','благодарю', '👍', '😁', '😂', '😄', 'хаха'] |
| 22 | +decrease_words = ['-', '👎'] |
| 23 | + |
| 24 | +users = {} |
| 25 | +user_karma = {} |
| 26 | + |
| 27 | +regex_letters = {'а' : ['а', 'a', '@'], |
| 28 | + 'б' : ['б', '6', 'b'], |
| 29 | + 'в' : ['в', 'b', 'v'], |
| 30 | + 'г' : ['г', 'r', 'g'], |
| 31 | + 'д' : ['д', 'd', 'g'], |
| 32 | + 'е' : ['е', 'e'], |
| 33 | + 'ё' : ['ё', 'е', 'e'], |
| 34 | + 'ж' : ['ж', 'zh', '*'], |
| 35 | + 'з' : ['з', '3', 'z'], |
| 36 | + 'и' : ['и', 'u', 'i'], |
| 37 | + 'й' : ['й', 'u', 'y', 'i'], |
| 38 | + 'к' : ['к', 'k', 'i{', '|{'], |
| 39 | + 'л' : ['л', 'l', 'ji'], |
| 40 | + 'м' : ['м', 'm'], |
| 41 | + 'н' : ['н', 'h', 'n'], |
| 42 | + 'о' : ['о', 'o', '0'], |
| 43 | + 'п' : ['п', 'n', 'p', '/7'], |
| 44 | + 'р' : ['р', 'r', 'p'], |
| 45 | + 'с' : ['с', 'c', 's'], |
| 46 | + 'т' : ['т', 'm', 't'], |
| 47 | + 'у' : ['у', 'y', 'u'], |
| 48 | + 'ф' : ['ф', 'f'], |
| 49 | + 'х' : ['х', 'x', 'h', 'к', '}{', ')('], |
| 50 | + 'ц' : ['ц', 'c', 'u,'], |
| 51 | + 'ч' : ['ч', 'ch'], |
| 52 | + 'ш' : ['ш', 'sh'], |
| 53 | + 'щ' : ['щ', 'sch'], |
| 54 | + 'ь' : ['ь', 'b'], |
| 55 | + 'ы' : ['ы', 'bi'], |
| 56 | + 'ъ' : ['ъ'], |
| 57 | + 'э' : ['э', 'е', 'e'], |
| 58 | + 'ю' : ['ю', 'io'], |
| 59 | + 'я' : ['я', 'ya'], |
| 60 | +} |
| 61 | + |
| 62 | +last_top = None |
| 63 | + |
| 64 | +#Todo: |
| 65 | +#ignore karmaspam from users |
| 66 | +# def check_user_for_karma(user_id: int, dest_user_id: int): |
| 67 | +# try: |
| 68 | +# usr_ch = user_karma[user_id] |
| 69 | +# except: |
| 70 | +# return True |
| 71 | + |
| 72 | +def count_mats(message_text): |
| 73 | + count_mats : int = 0 |
| 74 | + for regex_letter in regex_letters: |
| 75 | + for regex_char in regex_letters[regex_letter]: |
| 76 | + messageText = message_text.replace(regex_char, regex_letter) |
| 77 | + |
| 78 | + for stopword in stopwords: |
| 79 | + if stopword.lower() in message_text: |
| 80 | + count_mats+=1 |
| 81 | + |
| 82 | + return count_mats |
| 83 | + |
| 84 | +def get_karma(user_id : int): |
| 85 | + user = users[user_id] |
| 86 | + |
| 87 | + replytext = f"Привіt {user['username']}, tвоя карма:\n\n" |
| 88 | + replytext += f"Карма: `{user['karma']}`\n" |
| 89 | + replytext += f"Повідомлень: `{user['total_messages']}`\n" |
| 90 | + replytext += f"Матюків: `{user['total_mats']}`" |
| 91 | + replytext += '' |
| 92 | + |
| 93 | + replytext = replytext.replace('_', '\\_') |
| 94 | + |
| 95 | + return replytext |
| 96 | + |
| 97 | +def add_or_update_user(user_id: int, username: str, mats_count: int): |
| 98 | + try: |
| 99 | + users[user_id]['total_messages'] += 1 |
| 100 | + users[user_id]['total_mats'] += mats_count |
| 101 | + except: |
| 102 | + users[user_id] = {} |
| 103 | + users[user_id]['total_messages'] = 1 |
| 104 | + users[user_id]['total_mats'] = mats_count |
| 105 | + users[user_id]['username'] = username |
| 106 | + users[user_id]['karma'] = 0 |
| 107 | + |
| 108 | + saveToFile(users) |
| 109 | + |
| 110 | +def increase_karma(dest_user_id: int, message_text: str): |
| 111 | + if dest_user_id == bot_id: |
| 112 | + if message_text in increase_words : |
| 113 | + return "дякую" |
| 114 | + |
| 115 | + new_karma = None |
| 116 | + _username = None |
| 117 | + is_changed = False |
| 118 | + |
| 119 | + replytext = "Ви " |
| 120 | + for increase_word in increase_words: |
| 121 | + if increase_word in message_text: |
| 122 | + users[dest_user_id]['karma'] += 1 |
| 123 | + new_karma = users[dest_user_id]['karma'] |
| 124 | + _username = users[dest_user_id]['username'] |
| 125 | + replytext += 'підняли ' |
| 126 | + is_changed = True |
| 127 | + break |
| 128 | + if not is_changed: |
| 129 | + for decrease_word in decrease_words: |
| 130 | + if decrease_word in message_text : |
| 131 | + users[dest_user_id]['karma'] -= 1 |
| 132 | + new_karma = users[dest_user_id]['karma'] |
| 133 | + _username = users[dest_user_id]['username'] |
| 134 | + replytext += 'зменшили ' |
| 135 | + break |
| 136 | + if not is_changed: |
| 137 | + return |
| 138 | + |
| 139 | + replytext += f'карму користувача {_username} до вартості {new_karma}!' |
| 140 | + saveToFile(users) |
| 141 | + |
| 142 | + return replytext |
| 143 | + |
| 144 | +def stats(update, context): |
| 145 | + command = update.callback_query.data |
| 146 | + if command == 'refresh_top': |
| 147 | + replytext, reply_markup = getTop() |
| 148 | + replytext += f'\n`Оновлено UTC {datetime.datetime.utcnow()}`' |
| 149 | + query = update.callback_query |
| 150 | + query.edit_message_text(text=replytext, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN) |
| 151 | + return |
| 152 | + |
| 153 | +def getTop(): |
| 154 | + replytext = "*Топ 10 карми чату:*\n" |
| 155 | + users_list = [ v for k, v in users.items()] |
| 156 | + sorted_users_list = sorted(users_list, key = lambda i: i['karma'], reverse = True)[:10] |
| 157 | + |
| 158 | + for usr in sorted_users_list: |
| 159 | + username = usr['username'] |
| 160 | + karma = usr['karma'] |
| 161 | + replytext+=f'`{username}` - карма `{karma}`\n' |
| 162 | + |
| 163 | + replytext += "\n*Топ 10 актив чату:*\n" |
| 164 | + sorted_users_list = sorted(users_list, key = lambda i: i['total_messages'], reverse = True)[:10] |
| 165 | + |
| 166 | + for usr in sorted_users_list: |
| 167 | + username = usr['username'] |
| 168 | + messagescount = usr['total_messages'] |
| 169 | + replytext+=f'`{username}` - повідомлень `{messagescount}`\n' |
| 170 | + |
| 171 | + replytext += "\n*Топ 10 емоціонали чату:*\n" |
| 172 | + sorted_users_list = sorted(users_list, key = lambda i: i['total_mats'], reverse = True)[:10] |
| 173 | + |
| 174 | + for usr in sorted_users_list: |
| 175 | + username = usr['username'] |
| 176 | + matscount = usr['total_mats'] |
| 177 | + replytext+=f'`{username}` - матюків `{matscount}`\n' |
| 178 | + |
| 179 | + replytext += "\nКулдаун топу - 5 мінут" |
| 180 | + |
| 181 | + replytext = replytext.replace('@', '') |
| 182 | + |
| 183 | + keyboard = [[InlineKeyboardButton("Оновити", callback_data='refresh_top')]] |
| 184 | + reply_markup = InlineKeyboardMarkup(keyboard) |
| 185 | + return replytext, reply_markup |
| 186 | + |
| 187 | +def saveToFile(dict): |
| 188 | + f = codecs.open(database_filename, "w", "utf-8") |
| 189 | + f.write(str(users)) |
| 190 | + f.close() |
| 191 | + |
| 192 | +def autodelete_message(context): |
| 193 | + context.bot.delete_message(chat_id=context.job.context[0], message_id=context.job.context[1]) |
| 194 | + |
| 195 | +def openFile(): |
| 196 | + if os.path.isfile(database_filename): |
| 197 | + global users |
| 198 | + users = eval(open(database_filename, 'r', encoding= 'utf-8').read()) |
| 199 | + else: |
| 200 | + print ("File not exist") |
| 201 | + |
| 202 | +def on_msg(update, context): |
| 203 | + global last_top |
| 204 | + try: |
| 205 | + message = update.message |
| 206 | + if message is None: |
| 207 | + return |
| 208 | + |
| 209 | + if message.text == None: |
| 210 | + return |
| 211 | + |
| 212 | + is_old = False |
| 213 | + if message.date and (datetime.datetime.utcnow() - message.date).seconds > 300: |
| 214 | + is_old = True |
| 215 | + |
| 216 | + user_id = message.from_user.id |
| 217 | + username = message.from_user.name |
| 218 | + _chat_id = message.chat_id |
| 219 | + |
| 220 | + # chats control, you can define it in telegram bot father |
| 221 | + # if _chat_id != chat_id and user_id != admin_id: |
| 222 | + # return |
| 223 | + |
| 224 | + messageText = message.text.lower() |
| 225 | + |
| 226 | + # karma message |
| 227 | + if message.reply_to_message and message.reply_to_message.from_user.id and user_id != message.reply_to_message.from_user.id: |
| 228 | + karma_changed = increase_karma(message.reply_to_message.from_user.id, messageText) |
| 229 | + if karma_changed and not is_old: |
| 230 | + msg = context.bot.send_message(_chat_id, text=karma_changed) |
| 231 | + context.job_queue.run_once(autodelete_message, destruction_timeout, context=[msg.chat_id, msg.message_id]) |
| 232 | + |
| 233 | + # commands |
| 234 | + if messageText == "гіт" and not is_old: |
| 235 | + reply_text = 'github.com/awitwicki/rude\\_bot' |
| 236 | + msg = context.bot.send_message(_chat_id, text=reply_text, parse_mode=ParseMode.MARKDOWN) |
| 237 | + context.job_queue.run_once(autodelete_message, 300, context=[msg.chat_id, msg.message_id]) |
| 238 | + if messageText == "карма" and not is_old: |
| 239 | + reply_text = get_karma(user_id) |
| 240 | + msg = context.bot.send_message(_chat_id, text=reply_text, parse_mode=ParseMode.MARKDOWN) |
| 241 | + context.job_queue.run_once(autodelete_message, destruction_timeout, context=[msg.chat_id, msg.message_id]) |
| 242 | + if messageText == "топ" and not is_old: |
| 243 | + if not last_top or (datetime.datetime.utcnow() - last_top).seconds > 300: |
| 244 | + reply_text, reply_markup = getTop() |
| 245 | + msg = context.bot.send_message(_chat_id, text=reply_text, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN) |
| 246 | + context.job_queue.run_once(autodelete_message, 300, context=[msg.chat_id, msg.message_id]) |
| 247 | + last_top = datetime.datetime.utcnow() |
| 248 | + |
| 249 | + mats = count_mats(messageText) |
| 250 | + add_or_update_user(user_id, username, mats) |
| 251 | + |
| 252 | + except Exception as e: |
| 253 | + print(e) |
| 254 | + |
| 255 | +def main(): |
| 256 | + global bot_id |
| 257 | + |
| 258 | + openFile() |
| 259 | + |
| 260 | + updater = Updater(bot_token, use_context=True) |
| 261 | + |
| 262 | + dp = updater.dispatcher |
| 263 | + dp.add_handler(MessageHandler(Filters.text, on_msg, edited_updates = True)) |
| 264 | + dp.add_handler(CallbackQueryHandler(stats)) |
| 265 | + |
| 266 | + updater.start_polling() |
| 267 | + bot_id = updater.bot.id |
| 268 | + print("Bot is started.") |
| 269 | + updater.idle() |
| 270 | + |
| 271 | +if __name__ == '__main__': |
| 272 | + main() |
0 commit comments