在 Discord Bot 脚本中创建定时循环以重新加载网页网络抓取机器人

如何解决在 Discord Bot 脚本中创建定时循环以重新加载网页网络抓取机器人

我目前正在设计一个不和谐的机器人,它会抓取一个不断更新与 PBE 服务器相关的补丁的网页。我现在让机器人成功地通过 Heroku 运行。我遇到的问题是我想创建一个自动(定时循环)刷新来重新加载我请求的网站。目前,它只加载网站的一个实例,如果该网站发生更改/更新,我的任何内容都不会更新,因为我使用的是网站的“旧”请求。

有没有办法让我在函数中隐藏代码,以便我可以创建一个定时循环,或者我只需要围绕我的网站请求创建一个?那会怎样?谢谢!

from bs4 import BeautifulSoup
from urllib.request import urlopen
from discord.ext import commands
import discord

# what I want the commands to start with
bot = commands.Bot(command_prefix='!')

# instantiating discord client
token = "************************************"
client = discord.Client()

# begin the scraping of passed in web page
URL = "*********************************"
page = urlopen(URL)
soup = BeautifulSoup(page,'html.parser')
pbe_titles = soup.find_all('h1',attrs={'class': 'news-title'})  # using soup to find all header tags with the news-title
                                                                 # class and storing them in pbe_titles
linksAndTitles = []
counter = 0

# finding tags that start with 'a' as in a href and appending those titles/links
for tag in pbe_titles:
    for anchor in tag.find_all('a'):
        linksAndTitles.append(tag.text.strip())
        linksAndTitles.append(anchor['href'])

# counts number of lines stored inside linksAndTitles list
for i in linksAndTitles:
    counter = counter + 1
print(counter)

# separates list by line so that it looks nice when printing
allPatches = '\n'.join(str(line) for line in linksAndTitles[:counter])
# stores the first two lines in list which is the current pbe patch title and link
currPatch = '\n'.join(str(line) for line in linksAndTitles[:2])


# command that allows user to type in exactly what patch they want to see information for based off date
@bot.command(name='patch')
async def pbe_patch(ctx,*,arg):
    if any(item.startswith(arg) for item in linksAndTitles):
        await ctx.send(arg + " exists!")
    else:
        await ctx.send('The date you entered: ' + '"' + arg + '"' + ' does not have a patch associated with it or that patch expired.')


# command that displays the current,most up to date,patch
@bot.command(name='current')
async def current_patch(ctx):
    response = currPatch
    await ctx.send(response)


bot.run(token)

我玩过

while True:

循环,但每当我在其中嵌套任何内容时,我都无法访问其他地方的代码

解决方法

xcodebuild -create-xcframework -framework <path> [-framework <path>...] -output <path> xcodebuild -create-xcframework -library <path> [-headers <path>] [-library <path> [-headers <path>]...] -output <path> 有特殊的装饰器 discord 来定期运行一些代码

tasks

它会每 5 秒重复一次函数 from discord.ext import tasks @tasks.loop(seconds=5.0) async def scrape(): # ... your scraping code ... # ... your commands ... scrape.start() bot.run(token)


文档:tasks


在 Linux 上,我最终会使用标准服务 scrape 定期运行一些脚本。这个脚本可以抓取数据并保存在文件或数据库中,cron 可以从这个文件或数据库中读取。但是 discord 每 1 分钟检查一次任务,因此它不能更频繁地运行任务。


编辑:

最少的工作代码。

我使用为爬取学习而创建的页面 http://books.toscrape.com

我更改了一些元素。当有 cron 时不需要创建 client,因为 bot 是一种特殊的 bot

我保留 clienttitle 作为字典

link

所以以后更容易创建像

这样的文本
            {
                'title': tag.text.strip(),'link': url + anchor['href'],}

title: A Light in the ...
link: http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html

PEP 8 -- Style Guide for Python Code

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?