我很好奇如何每隔10秒循环一次我的代码。
我怎么能这样做,而不是Discord 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)
答案 0 :(得分: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
。它是一种更清晰的处理命令的方法。