与“异步”(如果事件循环正在运行)

时间:2019-03-16 12:17:14

标签: asynchronous async-await telethon telepot

我正在用Telepot和Telethon编写我的第一个电报机器人 我的主要代码是:

import sys
import asyncio
import random
import telepot
import telepot.aio
from telepot.aio.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove, ForceReply
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.namedtuple import InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent


async def on_chat_message(msg):

    global listenFromKeyboardUsername, listenFromKeyboardPassword, listenFromKeyboardLinkGroup

    content_type, chat_type, chat_id = telepot.glance(msg)
    chat_id = str(chat_id)

    if content_type == 'text':

        name = msg["from"]["first_name"]
        txt = msg['text']

        # stuff..

        elif userExistsInDb and userData['listenFromKeyboardLinkGroup'] and chat_id == doc.id:


            group = telegramGetMessages.checkGroup(txt)
            print(group)


TOKEN = "*******"

bot = telepot.aio.Bot(TOKEN)
answerer = telepot.aio.helper.Answerer(bot)

loop = asyncio.get_event_loop()
loop.create_task(MessageLoop(bot, {'chat': on_chat_message,
                                   'callback_query': on_callback_query}).run_forever())
print('Listening ...')

loop.run_forever()

从上面的代码中,我调用了checkGroup函数:

def checkGroup(hash):
    initClient()
    global result

    hash = hash.replace('https://t.me/joinchat/', '')
    with TelegramClient(name, api_id, api_hash) as client:
        result = client(functions.messages.CheckChatInviteRequest(hash=hash))

    if isinstance(result, ChatInvite):
        print('You are not inside the group')
        with TelegramClient(name, api_id, api_hash) as client:
            client(functions.messages.ImportChatInviteRequest(hash=hash))
            result = client(functions.messages.CheckChatInviteRequest(hash=hash))


    return result

我收到此错误的地方:

 RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")

然后我用checkGroup编辑async def checkGroup(hash): ..函数

but now I'm geting this error and I don't know what to do:
Task exception was never retrieved
future: <Task finished coro=<Router.route() done, defined at /home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py:213> exception=NotFound('No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups',)>
Traceback (most recent call last):
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 549, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/grpc/_channel.py", line 466, in _end_unary_response_blocking
    raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.NOT_FOUND
    details = "No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups"
    debug_error_string = "{"created":"@1552727386.760400590","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1039,"grpc_message":"No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups","grpc_status":5}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 244, in route
    return await _invoke(fn, msg, *args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/telepot/aio/helper.py", line 16, in _invoke
    return await fn(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/chatAsync.py", line 119, in on_chat_message
    database.updateUserData(chat_id, 'groups', 'nameGroup', txt)
  File "/home/ale/PycharmProjects/newTelegramBot/database.py", line 38, in updateUserData
    field: key,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/document.py", line 371, in update
    write_results = batch.commit()
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/batch.py", line 148, in commit
    metadata=self._client._rpc_metadata,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/gapic/firestore_client.py", line 946, in commit
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func
    on_error=on_error,
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/retry.py", line 179, in retry_target
    return target()
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/home/ale/PycharmProjects/newTelegramBot/venv/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.NotFound: 404 No document to update: projects/telegram-bot-4ee9f/databases/(default)/documents/users/585089661/data/groups
/usr/lib/python3.6/asyncio/base_events.py:1441: RuntimeWarning: coroutine 'checkGroup' was never awaited
  handle = None  # Needed to break cycles when an exception occurs.

我正在阅读,也许对于这个问题,最好使用delegatoBot,但是我不确定,因为我找不到很好的例子! 希望您能收到答复,如果您需要任何帮助,那就问一下! 谢谢

0 个答案:

没有答案