0.0.12-fixes

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

8
.idea/.gitignore 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 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 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 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>

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]
- исправления в коммандах /ask и /my
- исправление обработки случая без фото
-
- добавлен автомат состояний
- добавлена возможность высказаться "на кругу" без одобрения заявки
## [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.api import register_webhook, send_message
from bot.config import FEEDBACK_CHAT_ID
from bot.state import State
app = Sanic(name="welcomecenter")
app.config.REGISTERED = False
state = State()
@app.get('/')
async def register(req):
@ -36,33 +39,38 @@ async def handle(req):
# видимые сообщения
msg = update.get('message', update.get('edited_message'))
if msg:
if 'edited_message' in update:
msg['edit'] = True
if 'text' in msg:
if msg['chat']['id'] == msg['from']['id']:
print('private chat message')
if msg['text'].startswith('/my'):
handle_command_my(msg)
elif msg['text'].startswith('/unlink'):
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)
msg['edit'] = 'edited_message' in update
if msg['chat']['id'] == msg['from']['id']:
# сообщения в личке с ботом
print('private chat message')
if msg['text'].startswith('/my'):
handle_command_my(msg)
elif msg['text'].startswith('/unlink'):
handle_unlink(msg)
else:
handle_default(msg)
elif 'new_chat_member' in msg:
handle_join(msg)
elif 'left_chat_member' in msg:
handle_left(msg)
handle_feedback(msg, state)
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:
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:
@ -76,10 +84,6 @@ async def handle(req):
elif 'chat_join_request' in update:
print('chat join request')
handle_join_request(update['chat_join_request'])
# wtf
else:
print('unhandled update')
except Exception:

View File

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

View File

@ -14,23 +14,33 @@ def construct_unlink_buttons(actor):
'text': f'{identity} {username}',
'callback_data': 'unlink' + vouch
})
return { "inline_keyboard": [ buttons, ] }
return buttons
def handle_command_my(msg):
print(f'handle my command')
def handle_command_my(msg, state):
print('handle my command')
from_id = str(msg['from']['id'])
sender = Profile.get(from_id, msg)
handle_command_owner_my(msg)
# генерируем кнопки для всех, за кого поручились
reply_markup = construct_unlink_buttons(sender)
if msg['from'].get('language_code', 'ru') == 'ru':
body = 'Нажмите кнопки ниже, чтобы удалить ваши связи'
buttons = construct_unlink_buttons(sender)
reply_markup = { "inline_keyboard": [ buttons, ] }
if len(buttons) == 0:
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:
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)
print(r)
@ -47,7 +57,7 @@ def handle_command_owner_my(msg):
break
if owner_id:
owner = Profile.get(owner_id, msg)
uids, members = scan()
_uids, members = scan()
for mdata in members:
m = json.loads(mdata.decode('utf-8'))
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
def handle_default(msg):
print(f'default handler for all messages')
print('default handler for all messages')
chat_id = str(msg['chat']['id'])
from_id = str(msg['from']['id'])
sender = Profile.get(from_id, msg)
if msg['text'].startswith('/my'):
# команда в групповом чате
print(f'remove some messages in group chat')
print('remove some messages in group chat')
# удалить сообщение с командой /my
r = delete_message(chat_id, msg['message_id'])
print(r)
# показать новое сообщение с кнопкой
# для дополнительного поручения
show_request_msg(msg)
else:
# любое другое сообщение

View File

@ -7,21 +7,28 @@ from bot.storage import storage, Profile
from bot.config import FEEDBACK_CHAT_ID
def handle_feedback(msg):
def handle_feedback(msg, state):
mid = msg['message_id']
cid = msg['chat']['id']
if msg['text'] == '/start':
r = send_message(cid, 'Напишите своё сообщение для администрации чата')
print(r)
else:
r = forward_message(cid, mid, FEEDBACK_CHAT_ID)
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
}))
uid = msg['from']['id']
if state.is_talking(uid):
r = forward_message(cid, mid, state.talking[uid])
print(r)
state.aho(uid)
else:
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}')
if stored_feedback:
print(f'handle answer from support')
print('handle an answer from feedback group')
stored_feedback = json.loads(stored_feedback)
r = send_message(f'{stored_feedback["chat_id"]}', msg['text'], reply_to=stored_feedback["message_id"])
print(r)

View File

@ -3,6 +3,7 @@ from bot.utils.mention import mention, userdata_extract
from bot.storage import storage
def show_request_msg(msg):
print("showing request with button")
chat_id = str(msg['chat']['id'])
from_id = str(msg['from']['id'])
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]