【问题标题】:How would I have a Discord bot (made in Python) go to a website and fetch a number from the website?我如何让 Discord 机器人(用 Python 制作)访问网站并从网站获取号码?
【发布时间】:2020-12-20 18:45:10
【问题描述】:

所以我想创建一个机器人,它会去一个网站并从网站上获取一个号码。所以让我们说我们有一个这样的网站 A basic website

我希望我的机器人找到该数字的值是 5,然后发布一条消息说“数字是 5!”非常感谢大家!

【问题讨论】:

  • 您正在寻找requests 模块。基本上,您需要在 API 端点上执行 GET 请求并在您的机器人中解析响应正文。
  • 对于解析,您可以使用 Beautiful Soup 之类的东西。

标签: discord discord.py


【解决方案1】:

您应该使用 discord.py 中已包含的aiohttprequests 将导致 blocking

这是一个获取数据的简单命令,可以是 JSON 格式,也可以是文本格式。

@bot.command()
async def get_info(ctx, *, link):
    async with aiohttp.ClientSession() as session:
        async with session.get(link) as r:
            if r.status == 200:
                info = await r.json()
                #or if it is text
                info = await r.text()
                
    await ctx.send(info)

简单用例

  • JSON: get_info https://uselessfacts.jsph.pl/random.txt
  • 文本: get_info https://uselessfacts.jsph.pl/random.json

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 2023-03-03
    相关资源
    最近更新 更多