我在python中编写了一个bot,bot函数:显示股票的价格,设定一个价格限制,当达到这个限制时,发送一个消息给不和。在这个阶段,机器人只能监视一个动作。如何使它是异步的,以便它可以同时监视多个股票,当达到限制时,它会发送一个特定的股票与价格已经达到目标的信息不一致。
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from config import settings
bot = commands.Bot(command_prefix = settings['prefix'], help_command=None)
@bot.event
async def on_message(message):
await bot.process_commands(message)
channel = message.channel
co = '{0.content}'.format(message).split()
tes=co[0]
if tes=='price':
yo=co[1]
print(yo)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0'
}
r = requests.get(
('https://finance.yahoo.com/quote/') + yo + ('?p=') + yo + ('.tsrc=fin-srch'),
headers=headers)
soup = BeautifulSoup(r.text, 'lxml')
content = soup.find('div', {"class": 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
print(content)
await channel.send(f'{yo} - {content}')
return content
elif tes=='limit':
p=co[1]
su=co[2]
price=float(su)
while True:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0'
}
r = requests.get(
('https://finance.yahoo.com/quote/') + p + ('?p=') + p + ('.tsrc=fin-srch'),
headers=headers)
soup = BeautifulSoup(r.text, 'lxml')
content = soup.find('div', {"class": 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
con=float(content)
if price<=con:
await channel.send("достиг")
break
print(content)
return content
bot.run(settings['token'])发布于 2021-05-31 06:48:31
如何使它们异步
为了使它们异步地使用库艾奥赫特而不是请求,遗憾的是,对于异步的漂亮汤,我们别无选择,但是我们可以使用遗嘱执行人。
你必须做的改变:
import aiohttp (在安装discord.py时自动安装aiohttp)bot.session = aiohttp.ClientSession()行之后)添加一个bot = commands.Bot...r = requests.get(
('https://finance.yahoo.com/quote/') + yo + ('?p=') + yo + ('.tsrc=fin-srch'),
headers=headers)至
async with bot.session.get(
f'https://finance.yahoo.com/quote/{yo}?p={yo}.tsrc=fin-srch',
headers=headers
) as r:
# we will also change `r.text` to `await r.text()`这主要是通过使用会话对象,获取网站的原始html。与请求相同的作业,但异步
soup = BeautifulSoup(r.text, 'lxml')
content = soup.find('div', {"class": 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text要使其成为异步,首先将其添加到函数中。
def scrape(html):
soup = BeautifulSoup(html, 'lxml')
content = soup.find('div', {"class": 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text
return content这只是将漂亮的汤代码封装在一个接受原始html和返回所需内容的函数中。现在您的on_message中没有其他东西,而是
content = soup.find('div', {"class": 'My(6px) Pos(r) smartphone_Mt(6px)'}).find('span').text做
content = await bot.loop.run_in_executor(None, scrape, await r.text())这将运行scrape函数中的代码,并将等待r.text()传递给它,它是原始的html。然后在函数中得到原始的html,找到我们的数据并返回它。在这里,我们获取返回的值并将其保存到一个名为content的变量中。
https://stackoverflow.com/questions/67768510
复制相似问题