all repos — python-meme-bot @ 4ec29db74a8529fff0ce3f9439f7c333d4749e44

Telegram Bot that uses PIL to compute light image processing.

better localization, fix bugs, balance slot
Marco Andronaco andronacomarco@gmail.com
Mon, 12 Sep 2022 15:54:03 +0200
commit

4ec29db74a8529fff0ce3f9439f7c333d4749e44

parent

dd64024e9c2abe30460ea3af2586ad2ad9f3f4ba

3 files changed, 120 insertions(+), 62 deletions(-)

jump to
M Constants.pyConstants.py

@@ -1,7 +1,10 @@

import logging +from telegram.ext import CallbackContext localization = { - 'us': { + 'en': { + 'name' : "English", + 'emoji' : "🇬🇧", 'welcome' : "Welcome to PILuAnimeBot!", 'sauce' : "Sauce 🍝", 'no_caption' : "No caption detected.",

@@ -11,7 +14,7 @@ 'disabled' : "disabled",

'unknown' : "Sorry, I didn't understand that command.", 'error': "An error has occurred. Please retry.", 'failed_effect': "Couldn't apply effect.", - 'not_enough_cash': "You don't have enough money!", + 'not_enough_cash': "You don't have enough money! Type /cash to reset it.", 'you_lost': "You lost...", 'you_won': "You won {:0.2f}$!", 'cash_result': " Your money: {:0.2f}$.",

@@ -19,10 +22,16 @@ 'reroll': "Reroll (-{:0.2f}$)",

'summary': "You bet {}$ and won a total of {}$.", 'current_bet': "{}, your current bet is {:0.2f}$.", 'current_cash': "{}, you currently have {:0.2f}$ in your account.", - 'no_autospin': "Sorry, multiple spins are disabled in group chats." - + 'cash_reset': "{}, your cash has been reset to {:0.2f}$. You can do this once per day.", + 'cash_reset_fail': "{}, you have 0$ in your account and you cannot reset it today. Come back tomorrow.", + 'no_autospin': "Sorry, multiple spins are disabled in group chats.", + 'current_language': "Current language: {}.\nChoices: {}\nType \"/lang <code>\" to change it.", + 'invalid_language': "Invalid language.", + 'language_set': "Language set: {}", }, 'it': { + 'name': "Italiano", + 'emoji' : "🇮🇹", 'welcome' : "Benvenuto da PILuAnimeBot!", 'sauce' : "Salsa 🍝", 'no_caption' : "Scrivi un testo per favore.",

@@ -32,7 +41,7 @@ 'disabled' : "disabilitata",

'unknown' : "Non ho capito.", 'error': "Qualcosa è andato storto, riprova.", 'failed_effect': "Impossibile applicare l'effetto.", - 'not_enough_cash': "Saldo insufficiente!", + 'not_enough_cash': "Saldo insufficiente! Usa /cash per ripristinarlo.", 'you_lost': "Hai perso...", 'you_won': "Hai vinto {:0.2f}€!", 'cash_result': " Saldo: {:0.2f}€.",

@@ -40,9 +49,20 @@ 'reroll': "Riprova (-{:0.2f}€)",

'summary': "Hai giocato {}€ e vinto un totale di {}€.", 'current_bet': "{}, il tuo bet attuale è {:0.2f}€.", 'current_cash': "{}, il tuo saldo attuale è {:0.2f}€.", - 'no_autospin': "Gli spin multipli sono disabilitati nelle chat di gruppo." + 'cash_reset': "{}, il tuo saldo è stato ripristinato a {:0.2f}€. Puoi farlo una volta al giorno.", + 'cash_reset_fail': "{}, il tuo saldo è 0€ e non puoi più resettarlo oggi. Riprova domani.", + 'no_autospin': "Gli spin multipli sono disabilitati nelle chat di gruppo.", + 'current_language': "Lingua attuale: {}.\nAltre lingue: {}\nScrivi \"/lang <codice>\" per cambiarla.", + 'invalid_language': "Questa lingua non esiste.", + 'language_set': "Lingua impostata: {}", }, } +langs = localization.keys() +default_lang = "en" + +n_entries = len(localization[default_lang].keys()) +for i in langs: + assert(n_entries == len(localization[i].keys())) def format_author(user):

@@ -50,7 +70,22 @@ if user.username is not None:

return user.full_name + f" ({user.username})" return user.full_name -def get_localized_string(text, lang='us'): +def format_lang(lang: str): + try: + return f"{localization[lang]['name']} {localization[lang]['emoji']}" + except KeyError: + return 'Unknown' + +def get_lang(context: CallbackContext): + try: + return context.chat_data["lang"] + except KeyError: + context.chat_data["lang"] = default_lang + return default_lang + +def get_localized_string(text:str, context:CallbackContext): + lang = get_lang(context) + try: return localization[lang][text] except KeyError:

@@ -125,13 +160,13 @@ 64: (3, "seven"),

} win_table = { - (3, "seven"): 50, - (3, "bar"): 20, - (3, "lemon"): 10, - (3, "grape"): 5, + (3, "seven"): 20, + (3, "bar"): 5, + (3, "lemon"): 3, + (3, "grape"): 2, - (2, "seven"): 10, - (2, "bar"): 5, - (2, "lemon"): 2, - (2, "grape"): 1 + (2, "seven"): 4, + (2, "bar"): 2, + (2, "lemon"): 1, + (2, "grape"): 0.5 }
M Games.pyGames.py

@@ -10,11 +10,10 @@ lastreset_default = date(1970, 1, 1)

cash_default = 5000 bet_default = 50 slot_emoji = '🎰' -lang = 'us' def read_arg(context: CallbackContext, default=None, cast=int): try: - return cast(context.args[0]) + return cast(context.args[0].replace(",", ".").replace("€", "")) except (TypeError, IndexError, ValueError): return default

@@ -30,17 +29,7 @@ print(f"set {key} to {str(default)}")

return set_user_value(context, key, default) def get_cash(context: CallbackContext): - cash = get_user_value(context, "cash", cash_default) - - if cash == 0: - lastreset = get_lastreset(context) - today = date.today() - - if lastreset < today: - set_lastreset(context, today) - cash = set_cash(context, cash_default) - - return cash + return get_user_value(context, "cash", cash_default) def set_cash(context: CallbackContext, amount: int): return set_user_value(context, "cash", amount)

@@ -63,12 +52,12 @@ bet = get_bet(context)

cash = get_cash(context) if cash < bet: - context.bot.send_message(chat_id=id, text=l("not_enough_cash", lang)) + context.bot.send_message(chat_id=id, text=l("not_enough_cash", context)) return None cash = set_cash(context, cash - bet) - message = context.bot.send_dice(chat_id=id, emoji=slot_emoji) + message = context.bot.send_dice(chat_id=id, emoji=slot_emoji, disable_notification=True) multiplier = get_multiplier(message.dice.value)

@@ -76,12 +65,12 @@ win = bet * multiplier

cash = set_cash(context, cash + win) - text = l("you_lost", lang) if win == 0 else l("you_won", lang).format(win / 100) + text = l("you_lost", context) if win == 0 else l("you_won", context).format(win / 100) - text += l("cash_result", lang).format(cash / 100) + text += l("cash_result", context).format(cash / 100) time.sleep(2) - context.bot.send_message(chat_id=id, text=text, reply_markup=markup) + context.bot.send_message(chat_id=id, text=text, reply_markup=markup, disable_notification=True) return win def spin(update: Update, context: CallbackContext):

@@ -92,10 +81,10 @@ amount = read_arg(context, 1)

if amount > 1 and update.effective_chat.type != 'private': amount = 1 - context.bot.send_message(chat_id=update.effective_chat.id, text=l("no_autospin", lang)) + context.bot.send_message(chat_id=update.effective_chat.id, text=l("no_autospin", context)) if amount == 1: - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("reroll", lang).format(bet), callback_data="callback_1")]]) + markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("reroll", context).format(bet), callback_data="callback_1")]]) _spin(context=context, id=update.effective_chat.id, markup=markup) else: amount = max(1, min(amount, autospin_cap))

@@ -110,9 +99,9 @@

count += 1 total_win += win - result = l("summary", lang).format(count * bet, total_win / 100) + result = l("summary", context).format(count * bet, total_win / 100) markup = "" #InlineKeyboardMarkup([[InlineKeyboardButton(text="Altri {} spin (-{}€)".format(amount, bet * amount), callback_data="callback_2")]]) - context.bot.send_message(chat_id=update.effective_chat.id, text=result, reply_markup=markup) + context.bot.send_message(chat_id=update.effective_chat.id, text=result, reply_markup=markup, disable_notification=False) def bet(update: Update, context: CallbackContext):

@@ -123,13 +112,28 @@ bet = set_bet(context, int(amount * 100))

else: bet = get_bet(context) - result = l("current_bet", lang).format(c.format_author(update.effective_user), bet / 100) + result = l("current_bet", context).format(c.format_author(update.effective_user), bet / 100) context.bot.send_message(chat_id=update.effective_chat.id, text=result) def cash(update: Update, context: CallbackContext): cash = get_cash(context) / 100 - result = l("current_cash", lang).format(c.format_author(update.effective_user), cash) - context.bot.send_message(chat_id=update.effective_chat.id, text=result) + + if cash == 0: + lastreset = get_lastreset(context) + today = date.today() + + if lastreset < today: + set_lastreset(context, today) + cash = set_cash(context, cash_default) + + result = l("cash_reset", context).format(c.format_author(update.effective_user), cash / 100) + return update.message.reply_text(text=result) + else: + return update.message.reply_text(text=l("cash_reset_fail", context).format(c.format_author(update.effective_user))) + + + result = l("current_cash", context).format(c.format_author(update.effective_user), cash) + return update.message.reply_text(text=result) def get_multiplier(value: int):
M main.pymain.py

@@ -1,7 +1,7 @@

from PIL import Image from Api import get_random_image, rating_normal, rating_lewd from Effects import img_to_bio, tt_bt_effect, bt_effect, splash_effect, wot_effect, text_effect -from Constants import get_localized_string as l, format_author +from Constants import get_localized_string as l, format_author, format_lang, langs, get_lang from Games import spin, bet, cash from dotenv import load_dotenv

@@ -13,8 +13,6 @@

from telegram.error import TelegramError from telegram.ext import Updater, CallbackContext, CallbackQueryHandler, CommandHandler, MessageHandler, Filters, PicklePersistence from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton - -lang = 'us' def _get_message_content(message):

@@ -71,7 +69,7 @@ if image is None:

logging.warning("Getting Image failed") raise TelegramError("bad image") - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]]) + markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", context), url=url)]]) if bio: return image, markup

@@ -117,7 +115,7 @@

return content, image, markup def start(update: Update, context: CallbackContext): - context.bot.send_message(chat_id=update.effective_chat.id, text=l("welcome", lang)) + context.bot.send_message(chat_id=update.effective_chat.id, text=l("welcome", context)) def set_lewd(update: Update, context: CallbackContext):

@@ -127,7 +125,7 @@ except KeyError:

output = True context.chat_data['lewd'] = output - message = l("lewd_toggle", lang).format(l("enabled", lang) if output else l("disabled", lang)) + message = l("lewd_toggle", context).format(l("enabled", context) if output else l("disabled", context)) context.bot.send_message(chat_id=update.effective_chat.id, text=message)

@@ -157,7 +155,7 @@ logging.warning("Getting Image failed")

raise TelegramError("bad image") image = img_to_bio(image) - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]]) + markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", context), url=url)]]) update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)

@@ -175,7 +173,7 @@ raise TelegramError("bad image")

return image = img_to_bio(image) - markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", lang), url=url)]]) + markup = InlineKeyboardMarkup([[InlineKeyboardButton(text=l("sauce", context), url=url)]]) update.message.reply_photo(photo=image, parse_mode="markdown", reply_markup=markup)

@@ -253,13 +251,13 @@

content, image, markup = _get_all(update, ttbt_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = tt_bt_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -269,13 +267,13 @@

content, image, markup = _get_all(update, tt_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = tt_bt_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -284,13 +282,13 @@

content, image, markup = _get_all(update, tt_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = bt_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -299,13 +297,13 @@

content, image, markup = _get_all(update, splash_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = splash_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -314,13 +312,13 @@

content, image, markup = _get_all(update, wot_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = wot_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -329,13 +327,13 @@

content, image, markup = _get_all(update, wot_check, context) if image is None: - update.message.reply_text(l("no_caption", lang)) + update.message.reply_text(l("no_caption", context)) return image = text_effect(content, image) if image is None: - update.message.reply_text(l("failed_effect", lang)) + update.message.reply_text(l("failed_effect", context)) update.message.reply_photo(photo=image, reply_markup=markup)

@@ -343,6 +341,25 @@ def caps(update: Update, context: CallbackContext):

_, reply, _ = _get_reply(update.message.reply_to_message, ' '.join(context.args)) context.bot.send_message(chat_id=update.effective_chat.id, text=reply.upper()) + +def lang(update: Update, context: CallbackContext): + try: + selected = str(context.args[0]) + except IndexError: + selected = None + + if selected is None: + lang = format_lang(get_lang(context)) + choices = ", ".join(langs) + "." + return update.message.reply_text(text=l("current_language", context).format(lang, choices)) + + if selected not in langs: + update.message.reply_text(text=l("invalid_language", context)) + return + + context.chat_data["lang"] = selected + + update.message.reply_text(text=l("language_set", context).format(format_lang(selected))) def unknown(update: Update, context: CallbackContext): logging.info(f"User {update.message.from_user.full_name} sent {update.message.text_markdown_v2} and I don't know what that means.")

@@ -352,7 +369,7 @@ try:

raise context.error except TelegramError as e: logging.error("TelegramError! " + str(e)) - context.bot.send_message(chat_id=update.effective_chat.id, text=l('error', lang)) + context.bot.send_message(chat_id=update.effective_chat.id, text=l('error', context)) def _add_effect_handler(dispatcher, command: str, callback): dispatcher.add_handler(CommandHandler(command, callback))

@@ -364,13 +381,15 @@ updater = Updater(token=os.getenv("token"),

persistence=PicklePersistence(filename='bot-data.pkl', store_bot_data=False, store_callback_data=False, - store_user_data=False)) + #store_user_data=False + )) dispatcher = updater.dispatcher dispatcher.add_error_handler(error_callback) # commands dispatcher.add_handler(CommandHandler('start', start)) + dispatcher.add_handler(CommandHandler('lang', lang)) dispatcher.add_handler(CommandHandler('lewd', set_lewd)) dispatcher.add_handler(CommandHandler('caps', caps)) dispatcher.add_handler(CommandHandler('pic', pic))