【问题标题】:Python - Discord Bot Loop Command and Send Messages in Private MessagesPython - Discord Bot 循环命令并在私人消息中发送消息
【发布时间】:2018-07-24 17:31:10
【问题描述】:

我很好奇如何每 10 秒循环一次我的代码的这一部分。

我将如何做到这一点,而不是 Discord API 在 !price 执行时私下向您发送价格,而不是通常在频道中发送消息?

import requests
import discord
import asyncio

url = 'https://cryptohub.online/api/market/ticker/PLSR/'
response = requests.get(url)
data = response.json()['BTC_PLSR']

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print("PULSAR 4 LIFE")
    print('------')

    price = print('Price:', data['last'])
    pulsar = float(data['last'])
    pulsarx = "{:.9f}".format(pulsar)

    await client.change_presence(game=discord.Game(name="PLSR Price: " + pulsarx))


@client.event
async def on_message(message):
    if message.content.startswith('!price'):
        url = 'https://cryptohub.online/api/market/ticker/PLSR/'
        response = requests.get(url)
        data = response.json()['BTC_PLSR']
        price = print('PLSR Price:', data['last'])
        pulsar = float(data['last'])
        pulsarx = "{:.9f}".format(pulsar)
        await client.send_message(message.channel, 'Price of PULSAR: ' + pulsarx)

【问题讨论】:

  • 你想循环哪一部分?
  • 我想在它从 API URL 请求信息的地方循环。所以基本上信息每隔一段时间就会更新一次。
  • 基本上每 10 秒发送一次用户的 dms 垃圾邮件? o.o
  • 哦,没有。它显示在右上角的“正在播放”状态下。它不会向任何人发送垃圾邮件,我只是想要它,所以当他们输入 !price 时,它​​会将价格发送给他们,而不是在公共聊天中。我希望它反复循环,以便它不断准确地更新价格。

标签: python python-3.x discord


【解决方案1】:

首先,您不应该使用requests 模块,因为它不是异步的。这意味着,一旦您发送请求,您的机器人将挂起,直到请求完成。相反,请使用aiohttp。至于 dming 用户,只需更改目的地即可。至于循环,一个while循环就可以了。

import aiohttp
import discord
import asyncio

client = discord.Client()
url = 'https://cryptohub.online/api/market/ticker/PLSR/'

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print("PULSAR 4 LIFE")
    print('------')

    async with aiohttp.ClientSession() as session:
        while True:
            async with session.get(url) as response:
                data = await response.json()
                data = data['BTC_PLSR']
                print('Price:', data['last'])
                pulsar = float(data['last'])
                pulsarx = "{:.9f}".format(pulsar)
                await client.change_presence(game=discord.Game(name="PLSR Price: " + pulsarx))
                await asyncio.sleep(10) #Waits for 10 seconds


@client.event
async def on_message(message):
    if message.content.startswith("!price"):
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                data = await response.json()
                data = data['BTC_PLSR']
                pulsar = float(data['last'])
                pulsarx = "{:.9f}".format(pulsar)
                await client.send_message(message.author, 'Price of PULSAR: ' + pulsarx)

另外,我建议您查看discord.ext.commands。它是一种更简洁的命令处理方式。

【讨论】:

  • 老兄非常感谢你的救命稻草。我知道作为一名程序员我应该知道如何自己做到这一点,但由于个人健康相关问题,我无法学习,而是不得不不断地重新教自己一些东西,最终可能会发现缺乏答案。谢谢!
  • 如果每个人都知道如何自己做所有事情,这个网站就不会存在@BlakeXavier
猜你喜欢
  • 2020-12-23
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 2020-12-01
  • 2021-03-02
  • 2021-01-12
  • 2021-06-05
相关资源
最近更新 更多