Python Discord Bot循环命令并在私有消息中发送消息

2024-10-01 09:40:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

而我怎么能让它这样的不和谐API私信你的价格!价格执行而不是通常在渠道中传递消息?在

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)

Tags: importclienturlmessagedataresponserequestsprice
1条回答
网友
1楼 · 发布于 2024-10-01 09:40:39

首先,您不应该使用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。这是一种更干净的处理命令的方式。在

相关问题 更多 >