【问题标题】:Discord Python Multithread BotDiscord Python 多线程机器人
【发布时间】:2020-12-02 16:01:12
【问题描述】:

我从不和谐的用户那里获取用户输入并将其用于我的功能check。虽然,检查功能可能需要 30-50 秒才能完成,因为它必须等待网站加载等。我正在使用 requests.get。我怎样才能使这个多线程?

我当前的代码:

import json
import discord
import os
import bs4
from dotenv import load_dotenv
from discord.ext import commands
from datetime import datetime
import requests
import threading
import time
import re
from string import digits, ascii_letters

load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
bot = commands.Bot(command_prefix="$")
bot.remove_command('help')
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
url = 'hidden'
url2 = 'hidden'
url3 = 'hidden'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'}

whitelist = set(digits + ascii_letters + "#_[] -")
blacklist = set("")


@bot.event
async def on_ready():
    print("It's ready")


@bot.command()
async def check(ctx, *args):
    #my very advanced code start
    response = ""
    start_time = time.time()
    for arg in args:
        response = response + " " + arg
    #go on website and scrape with username 
    # my very advanced code end


bot.run(DISCORD_TOKEN)

我将大部分信息隐藏在我的函数check中。

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    requestsurllib 正在阻塞。请不要在您的异步代码中使用此库。请改用aiohttp

    这里是使用aiohttpdiscord.py的代码示例

    import aiohttp
    
    @bot.command()
    async def foo(ctx):
        async with aiohttp.ClientSession() as session:
            async with session.get('https://httpbin.org/json') as r:
                res = await r.json()
    

    不要为每个请求创建会话。很可能您需要为每个应用程序创建一个会话来完全执行所有请求。

    以下是如何保留一个可以从 cogs/extensions/functions 访问的会话

    @bot.event
    async def on_ready():
        await bot.wait_until_ready()
        bot.session = aiohttp.ClientSession()
    
    
    @bot.command()
    async def bar(ctx):
        async with bot.session.get('https://httpbin.org/json') as r:
            res = await r.json()
    

    但如果你真的想使用请求:

    def fetch():
        x = requests.get('https://httpsbin.org/json')
        return x.json()
    
    
    # in your asynchronous code
    response = await bot.loop.run_in_executor(None, fetch)
    

    aiohttp

    【讨论】:

    • 非常感谢。交换所有东西非常烦人,但非常值得。一个++
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2023-04-03
    • 2021-10-06
    • 2021-04-01
    • 1970-01-01
    • 2021-07-20
    • 2021-07-17
    相关资源
    最近更新 更多