version-0.2.1
This commit is contained in:
parent
a80727e97f
commit
02c4810437
|
@ -1,3 +1,10 @@
|
|||
## [0.2.1]
|
||||
|
||||
- реорганизация кодовой базы
|
||||
- сокращение логики обработчиков
|
||||
- отказ от хранения пользовательских данных
|
||||
- использование реакций
|
||||
|
||||
## [0.2.0]
|
||||
|
||||
- реорганизация кодовой базы
|
||||
|
|
|
@ -7,22 +7,31 @@ logger = logging.getLogger(__name__)
|
|||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
positive_reactions = [] # TODO: set positive reaction kinds
|
||||
|
||||
positive_reactions = ["👍", "❤", "🔥", "🥰", "👏", "🎉", "🙏", "👌", "🕊", "😍", "❤🔥", "🍓", "🍾", "💋", "😇", "🤝", "🤗", "💘", "😘"]
|
||||
announced_message = {
|
||||
"ru": "Запрос на вступление опубликован в чате, как только вас узнают и отреагируют - она будет принята",
|
||||
"en": "The join request is posted in the chat, once you are recognized and someone reacted to - it will be accepted"
|
||||
}
|
||||
async def handle_join_request(join_request):
|
||||
logger.info(f"handle join request {join_request}")
|
||||
user = join_request["from"]
|
||||
lang = user.get("language_code", "ru")
|
||||
|
||||
# показываем сообщение с кнопкой "поручиться"
|
||||
# показываем анонс с заявкой
|
||||
await show_announce(join_request)
|
||||
|
||||
# сообщаем пользователю, что опубликовали анонс его заявки
|
||||
await telegram_api("sendMessage", chat_id=user['id'], text=announced_message[lang])
|
||||
|
||||
|
||||
async def handle_reaction_on_request(update):
|
||||
chat_id = str(update["chat"]["id"])
|
||||
from_id = str(update["from"]["id"])
|
||||
|
||||
logger.debug(update)
|
||||
reaction = None # TODO: get reaction kind from update
|
||||
if reaction in positive_reactions:
|
||||
reaction = update.get("message_reaction")
|
||||
new_reaction = reaction.get("new_reaction")
|
||||
if new_reaction.get("emoji") in positive_reactions:
|
||||
# за пользователя поручились
|
||||
r = await telegram_api("approveChatJoinRequest", chat_id=chat_id, from_id=from_id)
|
||||
r = await telegram_api("approveChatJoinRequest", chat_id=chat_id, user_id=from_id)
|
||||
logger.debug(r)
|
||||
|
|
30
main.py
30
main.py
|
@ -3,49 +3,49 @@ import logging
|
|||
import signal
|
||||
import sys
|
||||
from aiohttp import ClientSession
|
||||
from handlers.commands import handle_command
|
||||
from handlers.messages_routing import messages_routing
|
||||
from handlers.handle_join_request import handle_join_request
|
||||
from handlers.handle_join_request import handle_join_request, handle_reaction_on_request
|
||||
from bot.config import BOT_TOKEN, FEEDBACK_CHAT_ID
|
||||
from bot.api import send_message
|
||||
from bot.api import telegram_api
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
state = dict()
|
||||
|
||||
api_url = f'https://api.telegram.org/bot{BOT_TOKEN}/'
|
||||
|
||||
|
||||
async def fetch(session, url):
|
||||
logger.debug(f"fetching: {url}")
|
||||
async with session.get(url) as response:
|
||||
logger.debug(response)
|
||||
return await response.json()
|
||||
|
||||
|
||||
async def main():
|
||||
async def start():
|
||||
logger.info("\tstarted")
|
||||
async with ClientSession() as session:
|
||||
offset = 0 # начальное значение offset
|
||||
while True:
|
||||
updates = await fetch(session, f"{api_url}getUpdates?offset={offset}")
|
||||
updates = await fetch(session, f"{api_url}getUpdates?offset={offset}&allowed_updates=['message', 'join_chat_request', 'message_reaction']")
|
||||
# logger.info('.' if updates['result'] == [] else updates)
|
||||
for update in updates.get("result", []):
|
||||
try:
|
||||
message = update.get("message")
|
||||
join_chat_request = update.get("join_chat_request")
|
||||
message_reaction = update.get("message_reaction")
|
||||
if message:
|
||||
text = message.get("text")
|
||||
if text.startswith('/'):
|
||||
await handle_command(message, state)
|
||||
else:
|
||||
await messages_routing(message, state)
|
||||
|
||||
elif join_chat_request:
|
||||
await handle_join_request(join_chat_request)
|
||||
elif message_reaction:
|
||||
await handle_reaction_on_request(message_reaction)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
logger.debug(update)
|
||||
import traceback
|
||||
text = traceback.format_exc()
|
||||
await send_message(FEEDBACK_CHAT_ID, text)
|
||||
await telegram_api("sendMessage", chat_id=FEEDBACK_CHAT_ID, text=text)
|
||||
|
||||
offset = update["update_id"] + 1
|
||||
|
||||
|
@ -53,7 +53,5 @@ async def main():
|
|||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
|
||||
# Запуск асинхронного цикла
|
||||
asyncio.run(main())
|
||||
asyncio.run(start())
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
[tool.poetry]
|
||||
name = "welcomecenterbot"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
description = "telegram group helper"
|
||||
authors = ["rainbowdev circle"]
|
||||
license = "Open Source"
|
||||
|
|
Loading…
Reference in New Issue
Block a user