0.0.12-fixes

This commit is contained in:
2023-09-11 20:02:29 +03:00
parent 2929c5f58f
commit f16b939d59
14 changed files with 136 additions and 53 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (welcome-webhook-bot)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/welcome-webhook-bot.iml" filepath="$PROJECT_DIR$/.idea/welcome-webhook-bot.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

17
.idea/welcome-webhook-bot.iml generated Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="py.test" />
</component>
</module>

View File

@@ -1,7 +1,8 @@
## [0.0.12] ## [0.0.12]
- исправления в коммандах /ask и /my - исправления в коммандах /ask и /my
- исправление обработки случая без фото - исправление обработки случая без фото
- - добавлен автомат состояний
- добавлена возможность высказаться "на кругу" без одобрения заявки
## [0.0.11] ## [0.0.11]

View File

@@ -12,10 +12,13 @@ from bot.handlers.callback_unlink import handle_unlink
from bot.handlers.handle_startup import handle_startup from bot.handlers.handle_startup import handle_startup
from bot.api import register_webhook, send_message from bot.api import register_webhook, send_message
from bot.config import FEEDBACK_CHAT_ID from bot.config import FEEDBACK_CHAT_ID
from bot.state import State
app = Sanic(name="welcomecenter") app = Sanic(name="welcomecenter")
app.config.REGISTERED = False app.config.REGISTERED = False
state = State()
@app.get('/') @app.get('/')
async def register(req): async def register(req):
@@ -36,33 +39,38 @@ async def handle(req):
# видимые сообщения # видимые сообщения
msg = update.get('message', update.get('edited_message')) msg = update.get('message', update.get('edited_message'))
if msg: if msg:
if 'edited_message' in update: msg['edit'] = 'edited_message' in update
msg['edit'] = True
if 'text' in msg: if msg['chat']['id'] == msg['from']['id']:
if msg['chat']['id'] == msg['from']['id']: # сообщения в личке с ботом
print('private chat message') print('private chat message')
if msg['text'].startswith('/my'): if msg['text'].startswith('/my'):
handle_command_my(msg) handle_command_my(msg)
elif msg['text'].startswith('/unlink'): elif msg['text'].startswith('/unlink'):
handle_unlink(msg) handle_unlink(msg)
else:
handle_feedback(msg)
elif str(msg['chat']['id']) == FEEDBACK_CHAT_ID:
print('feedback chat message')
if 'reply_to_message' in msg:
handle_answer(msg)
elif msg['text'] == '/graph':
await handle_command_graph(msg)
elif msg['text'].startswith('/ask'):
handle_command_ask(msg)
else: else:
handle_default(msg) handle_feedback(msg, state)
elif 'new_chat_member' in msg:
handle_join(msg) elif str(msg['chat']['id']) == FEEDBACK_CHAT_ID:
elif 'left_chat_member' in msg: # сообщения из группы обратной связи
handle_left(msg) print('feedback chat message')
if 'reply_to_message' in msg:
handle_answer(msg)
elif msg['text'] == '/graph':
await handle_command_graph(msg)
elif msg['text'].startswith('/ask'):
handle_command_ask(msg)
else: else:
print('message without text') # сообщения из всех остальных групп
cid = msg['chat']['id']
print(f'group {cid} chat message')
if 'text' in msg:
handle_default(msg)
elif 'new_chat_member' in msg:
handle_join(msg)
elif 'left_chat_member' in msg:
handle_left(msg)
# кнопки # кнопки
elif 'callback_query' in update: elif 'callback_query' in update:
@@ -76,10 +84,6 @@ async def handle(req):
elif 'chat_join_request' in update: elif 'chat_join_request' in update:
print('chat join request') print('chat join request')
handle_join_request(update['chat_join_request']) handle_join_request(update['chat_join_request'])
# wtf
else:
print('unhandled update')
except Exception: except Exception:

View File

@@ -3,8 +3,8 @@ from bot.handlers.send_button import show_request_msg
from bot.api import get_member from bot.api import get_member
def handle_command_ask(msg): def handle_command_ask(msg):
print(f'handling request resend') print('handling request resend')
cmd, chat_id, member_id = msg['text'].split(' ') _cmd, chat_id, member_id = msg['text'].split(' ')
chat_id = chat_id.replace('-', '-100') chat_id = chat_id.replace('-', '-100')
r = get_member(chat_id, member_id) r = get_member(chat_id, member_id)
print(r) print(r)

View File

@@ -14,23 +14,33 @@ def construct_unlink_buttons(actor):
'text': f'{identity} {username}', 'text': f'{identity} {username}',
'callback_data': 'unlink' + vouch 'callback_data': 'unlink' + vouch
}) })
return { "inline_keyboard": [ buttons, ] } return buttons
def handle_command_my(msg): def handle_command_my(msg, state):
print(f'handle my command') print('handle my command')
from_id = str(msg['from']['id']) from_id = str(msg['from']['id'])
sender = Profile.get(from_id, msg) sender = Profile.get(from_id, msg)
handle_command_owner_my(msg) handle_command_owner_my(msg)
# генерируем кнопки для всех, за кого поручились # генерируем кнопки для всех, за кого поручились
reply_markup = construct_unlink_buttons(sender) buttons = construct_unlink_buttons(sender)
reply_markup = { "inline_keyboard": [ buttons, ] }
if msg['from'].get('language_code', 'ru') == 'ru': if len(buttons) == 0:
body = 'Нажмите кнопки ниже, чтобы удалить ваши связи' if msg['from'].get('language_code', 'ru') == 'ru':
body = 'Вас ещё никто не узнал? Напишите, я передам нашему кругу'
else:
body = 'Nobody recognized you? Speak, I will pass your message to the circle'
r = send_message(from_id, body)
print(r)
chat_id = msg['chat']['id']
state.make_talking(from_id, chat_id)
else: else:
body = 'Unlink your connections pressing the buttons below' if msg['from'].get('language_code', 'ru') == 'ru':
body = 'Нажмите кнопки ниже, чтобы удалить ваши связи'
else:
body = 'Unlink your connections pressing the buttons below'
r = send_message(from_id, body, reply_markup=reply_markup) r = send_message(from_id, body, reply_markup=reply_markup)
print(r) print(r)
@@ -47,7 +57,7 @@ def handle_command_owner_my(msg):
break break
if owner_id: if owner_id:
owner = Profile.get(owner_id, msg) owner = Profile.get(owner_id, msg)
uids, members = scan() _uids, members = scan()
for mdata in members: for mdata in members:
m = json.loads(mdata.decode('utf-8')) m = json.loads(mdata.decode('utf-8'))
if owner_id in m['parents']: if owner_id in m['parents']:

View File

@@ -3,20 +3,21 @@ from bot.storage import Profile, storage
from bot.handlers.send_button import show_request_msg from bot.handlers.send_button import show_request_msg
def handle_default(msg): def handle_default(msg):
print(f'default handler for all messages') print('default handler for all messages')
chat_id = str(msg['chat']['id']) chat_id = str(msg['chat']['id'])
from_id = str(msg['from']['id']) from_id = str(msg['from']['id'])
sender = Profile.get(from_id, msg) sender = Profile.get(from_id, msg)
if msg['text'].startswith('/my'): if msg['text'].startswith('/my'):
# команда в групповом чате # команда в групповом чате
print(f'remove some messages in group chat') print('remove some messages in group chat')
# удалить сообщение с командой /my # удалить сообщение с командой /my
r = delete_message(chat_id, msg['message_id']) r = delete_message(chat_id, msg['message_id'])
print(r) print(r)
# показать новое сообщение с кнопкой # показать новое сообщение с кнопкой
# для дополнительного поручения
show_request_msg(msg) show_request_msg(msg)
else: else:
# любое другое сообщение # любое другое сообщение

View File

@@ -7,21 +7,28 @@ from bot.storage import storage, Profile
from bot.config import FEEDBACK_CHAT_ID from bot.config import FEEDBACK_CHAT_ID
def handle_feedback(msg): def handle_feedback(msg, state):
mid = msg['message_id'] mid = msg['message_id']
cid = msg['chat']['id'] cid = msg['chat']['id']
if msg['text'] == '/start': if msg['text'] == '/start':
r = send_message(cid, 'Напишите своё сообщение для администрации чата') r = send_message(cid, 'Напишите своё сообщение для администрации чата')
print(r) print(r)
else: else:
r = forward_message(cid, mid, FEEDBACK_CHAT_ID) uid = msg['from']['id']
support_msg_id = r['result']['message_id'] if state.is_talking(uid):
# сохранение айди сообщения в приватной переписке с ботом r = forward_message(cid, mid, state.talking[uid])
storage.set(f'fbk-{support_msg_id}', json.dumps({ print(r)
"author_id": msg["from"]["id"], state.aho(uid)
"message_id": mid, else:
"chat_id": cid r = forward_message(cid, mid, FEEDBACK_CHAT_ID)
})) print(r)
support_msg_id = r['result']['message_id']
# сохранение айди сообщения в приватной переписке с ботом
storage.set(f'fbk-{support_msg_id}', json.dumps({
"author_id": msg["from"]["id"],
"message_id": mid,
"chat_id": cid
}))
@@ -37,7 +44,7 @@ def handle_answer(msg):
# получение сохраненного информации о сообщении для ответа # получение сохраненного информации о сообщении для ответа
stored_feedback = storage.get(f'fbk-{support_msg_id}') stored_feedback = storage.get(f'fbk-{support_msg_id}')
if stored_feedback: if stored_feedback:
print(f'handle answer from support') print('handle an answer from feedback group')
stored_feedback = json.loads(stored_feedback) stored_feedback = json.loads(stored_feedback)
r = send_message(f'{stored_feedback["chat_id"]}', msg['text'], reply_to=stored_feedback["message_id"]) r = send_message(f'{stored_feedback["chat_id"]}', msg['text'], reply_to=stored_feedback["message_id"])
print(r) print(r)

View File

@@ -3,6 +3,7 @@ from bot.utils.mention import mention, userdata_extract
from bot.storage import storage from bot.storage import storage
def show_request_msg(msg): def show_request_msg(msg):
print("showing request with button")
chat_id = str(msg['chat']['id']) chat_id = str(msg['chat']['id'])
from_id = str(msg['from']['id']) from_id = str(msg['from']['id'])
lang = msg['from'].get('language_code', 'ru') lang = msg['from'].get('language_code', 'ru')

10
bot/state.py Normal file
View File

@@ -0,0 +1,10 @@
class State:
def __init__(self):
self.talking = dict()
def is_talking(self, uid):
return uid in self.talking
def make_talking(self, uid, cid):
self.talking[uid] = cid
def aho(self, uid):
del self.talking[uid]