Python - Discord Bot循环命令和私人消息中的发送消息

我很好奇如何每隔10秒循环一次我的代码 .

我将如何制作它而不是Discord API私人消息你价格!价格执行而不是通常在 Channels 中发送消息?

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)

回答(1)

2 years ago

首先,您不应该使用 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 . 它是一种更清晰的处理命令的方式 .