|
@@ -0,0 +1,69 @@
|
|
|
+import asyncio
|
|
|
+import logging
|
|
|
+import os
|
|
|
+
|
|
|
+import davtelepot
|
|
|
+
|
|
|
+from .messages import patreon_messages
|
|
|
+
|
|
|
+
|
|
|
+def is_patrons_list_file(update: dict):
|
|
|
+ return (update['document']['mime_type'] == 'text/csv'
|
|
|
+ and 'patron' in update['document']['file_name'])
|
|
|
+
|
|
|
+
|
|
|
+async def kick_unlisted_patrons(bot: davtelepot.bot.Bot):
|
|
|
+ for record in bot.db.query("SELECT u.telegram_id telegram_id, p.id patron_id FROM patrons p "
|
|
|
+ "LEFT JOIN users u ON u.id = p.user_id "
|
|
|
+ "WHERE p.tier IS NULL AND p.is_in_chat = 1"):
|
|
|
+ try:
|
|
|
+ await bot.kickChatMember(chat_id=bot.shared_data['bic_chat_id'],
|
|
|
+ user_id=record['telegram_id'])
|
|
|
+ bot.db.query(f"UPDATE patrons SET is_in_chat = 0 WHERE id = {record['patron_id']}")
|
|
|
+ except Exception as e:
|
|
|
+ logging.error(e)
|
|
|
+
|
|
|
+
|
|
|
+async def handle_patrons_list_file(bot: davtelepot.bot.Bot, update: dict, language: str):
|
|
|
+ file_name = davtelepot.utilities.get_secure_key(length=12)
|
|
|
+ while os.path.isfile(f'{bot.path}/data/{file_name}'):
|
|
|
+ file_name = davtelepot.utilities.get_secure_key(length=12)
|
|
|
+ await bot.download_file(file_id=update['document']['file_id'],
|
|
|
+ file_name=file_name,
|
|
|
+ path=f'{bot.path}/data')
|
|
|
+ patrons_list = davtelepot.utilities.csv_read(f'{bot.path}/data/{file_name}')
|
|
|
+ os.remove(f'{bot.path}/data/{file_name}')
|
|
|
+ with bot.db as db: # Unique SQL transaction
|
|
|
+ db.query("UPDATE patrons SET tier = NULL")
|
|
|
+ for patron in patrons_list:
|
|
|
+ db['patrons'].upsert(
|
|
|
+ dict(tier=1,
|
|
|
+ email=patron['email']),
|
|
|
+ ['email']
|
|
|
+ )
|
|
|
+ asyncio.ensure_future(kick_unlisted_patrons(bot=bot))
|
|
|
+ return bot.get_message('patreon', 'list_updated', language=language)
|
|
|
+
|
|
|
+
|
|
|
+def init(telegram_bot: davtelepot.bot.Bot):
|
|
|
+ telegram_bot.messages['patreon'] = patreon_messages
|
|
|
+ if 'patrons' not in telegram_bot.db.tables:
|
|
|
+ table = telegram_bot.db.create_table('patrons')
|
|
|
+ else:
|
|
|
+ table = telegram_bot.db.get_table('patrons')
|
|
|
+ if 'email' not in table.columns:
|
|
|
+ table.create_column('email', telegram_bot.db.types.string(320))
|
|
|
+ if 'tier' not in table.columns:
|
|
|
+ table.create_column('tier', telegram_bot.db.types.integer)
|
|
|
+ if 'user_id' not in table.columns:
|
|
|
+ table.create_column('user_id', telegram_bot.db.types.integer)
|
|
|
+ if 'is_in_chat' not in table.columns:
|
|
|
+ table.create_column('is_in_chat', telegram_bot.db.types.boolean)
|
|
|
+
|
|
|
+ @telegram_bot.document_handler(condition=is_patrons_list_file,
|
|
|
+ authorization_level='administrator')
|
|
|
+ async def _handle_patrons_list_file(bot: davtelepot.bot.Bot,
|
|
|
+ update: dict,
|
|
|
+ language: str):
|
|
|
+ return await handle_patrons_list_file(bot=bot, update=update,
|
|
|
+ language=language)
|