Python 异步IO在循环中等待事件

Python 异步IO在循环中等待事件,python,python-asyncio,Python,Python Asyncio,我的问题是我有用于事件侦听的脚本。连接到服务器后,事件侦听将在循环中启动。所以在函数main中连接服务器之后,我创建了一个循环 loop = asyncio.get_event_loop() asyncio.ensure_future(monitor(ts3conn, dbconn)) loop.run_forever() 现在,当我得到任何事件时,检查是否有语句,如果有,我必须等待函数或创建新任务?我想异步3个函数,1个main,一直在监听,以及当有人编写消息

我的问题是我有用于事件侦听的脚本。连接到服务器后,事件侦听将在循环中启动。所以在函数main中连接服务器之后,我创建了一个循环

loop = asyncio.get_event_loop()
        asyncio.ensure_future(monitor(ts3conn, dbconn))
        loop.run_forever()
现在,当我得到任何事件时,检查是否有语句,如果有,我必须等待函数或创建新任务?我想异步3个函数,1个main,一直在监听,以及当有人编写消息/加入通道时,在这个脚本中,当30个用户加入通道777(如果777==int(event['ctid']):)时,将创建的额外内容,同时有人将加入通道904(如果904==int(event['ctid']):,最后一个家伙必须等待,直到30个用户将被服务(我希望你理解)

我的代码:

import ts3
import time
import logging
import json
import pymysql.cursors
import pymysql
import asyncio
from logging.handlers import RotatingFileHandler

def main():
    with ts3.query.TS3ServerConnection(URI) as ts3conn:
        # connect to server instance, update name and go to specific channel
        ts3conn.exec_("use", sid=SID)
        ts3conn.exec_("clientupdate", client_nickname=CLIENT_NAME)
        myclid = ts3conn.exec_("whoami")[0]["client_id"]
        ts3conn.exec_("clientmove", clid=myclid, cid=JOIN_CHANNEL_ID)
        ts3conn.exec_("servernotifyregister", event="server")
        ts3conn.exec_("servernotifyregister", event="channel", id=0)
        ts3conn.exec_("servernotifyregister", event="textprivate")
        dbconn = pymysql.connect(host='localhost', user='root', password='', db='teamspeak')

        loop = asyncio.get_event_loop()
        asyncio.ensure_future(monitor(ts3conn, dbconn))
        loop.run_forever()

# Function handling the events and initiating activity logs
async def monitor(ts3conn, dbconn):
    # register for all events in server wide chat
    ts3conn.exec_("servernotifyregister", event="server")
    ts3conn.exec_("servernotifyregister", event="channel", id=0)
    ts3conn.exec_("servernotifyregister", event="textprivate")
    ts3conn.send_keepalive()
    while True:
        try:
            event = ts3conn.wait_for_event(timeout=10)[0]
        except ts3.query.TS3TimeoutError:
            ts3conn.send_keepalive()
        else:
            await asyncio.sleep(0.001)
            print(event)
            # ============= IF JOIN CHANNEL ===================
            if "ctid" in event.keys() and "clid" in event.keys() and int(event['ctid']) != 0:
                if 777 == int(event['ctid']):
                    asyncio.create_task(first(ts3conn, dbconn, event['clid']))
                    #ts3conn.exec_("clientkick", reasonid=4, clid=event['clid'])
                if 904 == int(event['ctid']):
                    asyncio.create_task(second(ts3conn, dbconn, event['clid']))
                    #ts3conn.exec_("clientkick", reasonid=4, clid=event['clid'])
            # ============= IF SEND MSG ===================
            if "msg" in event.keys() and "invokeruid" in event.keys() and 'serveradmin' not in str(event['invokeruid']):
                if event['msg'] == "!info":
                    print("info")
                    asyncio.create_task(first(ts3conn, dbconn, event['invokerid']))


async def first(ts3conn, dbconn, uid):
    try:
        print("first")
        user = ts3conn.exec_("clientinfo", clid=uid)
        if any(i in user[0]['client_servergroups'] for i in REG):
            try:
                sql = "SELECT * FROM users WHERE uid=%s"
                cursor = dbconn.cursor()
                cursor.execute(sql, (user[0]['client_unique_identifier']))
                c = cursor.fetchone()
                ts3conn.exec_("sendtextmessage", targetmode="1", target=uid, msg=f"register: {c}")
            except KeyError as e:
                print(e)
        else:
            ts3conn.exec_("sendtextmessage", targetmode="1", target=uid, msg=f"not register")
    except KeyError as e:
        print(f"keyerror: {e}")


async def second(ts3conn, dbconn, uid):
    try:
        user = ts3conn.exec_("clientinfo", clid=uid)
        if any(i in user[0]['client_servergroups'] for i in REG):
            try:
                sql = "SELECT * FROM users WHERE uid=%s"
                cursor = dbconn.cursor()
                cursor.execute(sql, (user[0]['client_unique_identifier']))
                c = cursor.fetchone()
                ts3conn.exec_("sendtextmessage", targetmode="1", target=uid, msg=f"1 out: {c}")
            except KeyError as e:
                print(e)
        else:
            ts3conn.exec_("sendtextmessage", targetmode="1", target=uid, msg=f"321123321321132")
    except KeyError as e:
        print(f"keyerror: {e}")



if __name__ == "__main__":
    with open('config.json') as config_file:
        config = json.load(config_file)

    try:
        SQLDATABASE = config["sqldatabase"]
        DATABASE = config["sqldatabase"]
        URI = config["uri"]
        SID = config["sid"]
        CLIENT_NAME = config["client_name"]
        JOIN_CHANNEL_ID = config["join_channel_id"]
        REG = config['zarejeya']

        if config["log_level"] == "CRITICAL":
            LOG_LEVEL = logging.CRITICAL
        elif config["log_level"] == "ERROR":
            LOG_LEVEL = logging.ERROR
        elif config["log_level"] == "WARNING":
            LOG_LEVEL = logging.WARNING
        elif config["log_level"] == "INFO":
            LOG_LEVEL = logging.INFO
        elif config["log_level"] == "DEBUG":
            LOG_LEVEL = logging.DEBUG
        else:
            LOG_LEVEL = logging.NOTSET
    except:
        print("Error parsing config")
        raise

    log_formatter = logging.Formatter("%(asctime)s - %(funcName)s - %(levelname)s - %(message)s")
    log_handler = RotatingFileHandler("ts3bot.log", mode='a', maxBytes=50 * 1024 * 1024, backupCount=2)
    log_handler.setFormatter(log_formatter)
    log_handler.setLevel(LOG_LEVEL)
    # noinspection PyRedeclaration
    logger = logging.getLogger("root")
    logger.setLevel(LOG_LEVEL)
    logger.addHandler(log_handler)

    while True:
        try:
            main()
        except Exception:
            logger.exception("Exception occurred and connection is closed")
            logger.info("Trying to restart in 30s")
            time.sleep(30)


我需要类似于discord机器人的东西:
但是我不能在这里运行…

您可以使用
循环。create_task()
在后台运行异步方法而不阻塞当前循环


你可以在官方文件中了解更多

您可以使用
loop.create_task()
在后台运行异步方法,而不阻塞当前循环

你可以在官方文件中了解更多

调用
await()
将暂停当前协同程序,并且只有在返回等待的coro时才会恢复

在您的代码中,
monitor
coroutine将连续处理传入事件。。因此,如果发生任何事件,监视器将在
first()/second()
coro上等待,这将使
monitor
coro再次处于暂停状态。。。这是同步的。。异步没有真正的好处。。相反,这会使性能更差

事件处理协程,
first()
second()
可以转换为任务。。您可以使用
asyncio.create_task()
将协同程序包装到任务。。轮到它时,它将被安排在同一事件循环中执行。并且在任务执行时,调用coro(在本例中为
monitor()
)不会挂起。。任务本身是一个可等待的,因此调用任务上的等待将使被调用方暂停

您可能希望保存创建的任务(在create_task()过程中返回)以供以后的操作使用。。就像停止它,等待它

await task # To await for the task to complete, suspends to current coro.
如果您希望取消活动任务,则该任务将抛出CanceledError,该错误必须得到妥善处理

例如:

async def stop_task(task):
    if not task:
        return
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass
调用
await()

在您的代码中,
monitor
coroutine将连续处理传入事件。。因此,如果发生任何事件,监视器将在
first()/second()
coro上等待,这将使
monitor
coro再次处于暂停状态。。。这是同步的。。异步没有真正的好处。。相反,这会使性能更差

事件处理协程,
first()
second()
可以转换为任务。。您可以使用
asyncio.create_task()
将协同程序包装到任务。。轮到它时,它将被安排在同一事件循环中执行。并且在任务执行时,调用coro(在本例中为
monitor()
)不会挂起。。任务本身是一个可等待的
,因此调用任务上的等待将使被调用方暂停

您可能希望保存创建的任务(在create_task()过程中返回)以供以后的操作使用。。就像停止它,等待它

await task # To await for the task to complete, suspends to current coro.
如果您希望取消活动任务,则该任务将抛出CanceledError,该错误必须得到妥善处理

例如:

async def stop_task(task):
    if not task:
        return
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass

相似:相似:当我将asyncio.create_任务添加到第一个和第二个时,它看起来像函数主工作异步,但第一个和第二个函数不会执行,我不必等待第一个或第二个函数,我想让它在后台运行,而不会得到任何结果。函数是不可抢占的方法。。他们必须自愿发出信号,表示他们可以被搁置。。等待。。如果ts3conn.wait\u for\u事件不是wait语句,则在创建任务后尝试使用wait asyncio.sleep(0.01)。通过这种方式,它将监视器置于挂起状态,并为first()/second()提供执行空间。在阅读您的消息后,我已经这样做了,我在
之后添加了wait asyncio.sleep(0.001),而True:try:event=ts3conn.wait_for_event(timeout=10)[0]除了ts3.query.TS3TimeoutError:ts3conn.send_keepalive()其他:
和。。。。当用户加入777频道时,什么也没发生,当他离开时,消息被发送。。。我想,我需要在别的地方等待,但在哪里。。。我已经在顶部添加了新代码,您不应该在while循环中添加wait asyncio.sleep()吗?很明显,我的错,谢谢你的帮助,它现在可以工作了:)当我把asyncio.create_任务添加到第一个和第二个时,它看起来像函数主工作异步,但函数第一个和第二个不会执行,我不必等待函数第一个或第二个,我想让它在后台运行而不产生任何结果,因为例程是不可抢占的方法。。他们必须自愿发出信号,表示他们可以被搁置。。等待。。如果ts3conn.wait\u for\u事件不是wait语句,则在创建任务后尝试使用wait asyncio.sleep(0.01)。通过这种方式,它将监视器置于挂起状态,并为first()/second()提供执行空间。在阅读您的消息后,我已经这样做了,我在
之后添加了wait asyncio.sleep(0.001),而True:try:event=ts3conn.wait_for_event(timeout=10)[0]除了ts3.query.TS3TimeoutError:ts3conn.send_keepalive()其他:
和。。。。当用户加入777频道时,什么也没发生,当他离开时,消息被发送。。。我想,我需要在别的地方等待,但在哪里。。。我已经在顶部添加了新代码,您不添加wait asyncio吗