微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Discord Bot Image Loop (Python)

如何解决Discord Bot Image Loop (Python)

所以这个 discord Bot 是由三个 Python 脚本组成的。

main.py

GoodAnimeMemes.py

webserver.py

脚本说明:

webserver.py 脚本用于让我的 discord 机器人保持活动状态(24/7 运行)。

GoodAnimeMemes.py 脚本应该从网站上查找图像;在这种情况下,Reddit 并下载它们。

并且 main.py 脚本应该运行 GoodAnimeMemes.py 脚本以循环重新创建新图像,并通过我的 discord 服务器发送它们。

然而,这是我遇到的问题,不知道如何解决

如何在每次循环结束时重新加载网页,而不使用 webdriver?

我使用的网站(Replit.com)不支持 webdrive 库。

我的代码有效。但分开。如果我运行 GoodAnimeMemes.py,它将根据网站最新的 5 张图片下载新图片。 如果我运行 main.py 它将发送我之前运行的图像。 但是,如果网站发布了新图片它不会自动下载新图片,而是不断发送相同的图片... 为了这篇文章比较小,我把 main.py 做成只发一张图片

有什么建议吗?

ma​​in.py

import os
import time
import discord
from discord.ext import commands
import GoodAnimeMemes
from webserver import keep_alive

bot = commands.Bot(command_prefix='$')

# Server info display in Console when bot runs
@bot.event
async def on_ready():
    guild_count = 0
    for guild in bot.guilds:
        print(f"- {guild.id} (name: {guild.name})")
        guild_count = guild_count + 1
    print("Bot is in " + str(guild_count) + " guilds.")

# Bot; when command is used,then bot starts
@bot.event
async def on_message(message):
    while message.content == "/start":
        # Obtain data
        exec(open("GoodAnimeMemes.py").read())

        # Send data 1
        print("! Downloading image...")
        await message.channel.send("hey dirtbag",file=discord.File("anime1.jpg"))
        print("Sent!")
        time.sleep(60)
        os.remove("anime1.jpg")
        # Pause bot for 4hrs (14400sec)
    else:
      pass


keep_alive()
TOKEN = os.environ['disCORD_TOKEN']
bot.run(TOKEN)

GoodAnimeMemes.py

import requests
from bs4 import BeautifulSoup
import time


headers = {'User-Agent': xxxxxxxxxxxxxxxxxxxxxxxxxx}

url = "https://www.reddit.com/r/Animemes/"


r = requests.get(url,headers=headers)
# Check connection to website
if r.status_code == 200:
  print("Connected to website!")
  time.sleep(0.5)
elif r.status_code == 400:
  print("Page does not exist...")
  time.sleep(0.5)
elif r.status_code == 500:
  print("Unauthorized access!")
  time.sleep(0.5)
else:
  pass


soup = BeautifulSoup(r.text,'html.parser')
# Print Title of Website
print(soup.title.text)
time.sleep(0.5)


links = soup.find_all("img",{"alt": "Post image"})
# Print How Many Links There Are
print("There are",len(links),"links to work with.")
time.sleep(0.8)


images = []
for link in links:
  if link.has_attr('src'):
    # append individual URL to "images" list
    images.append(link['src'])

# Set initial n value
n = 0

# Loop through list of URLs and download each with name "anime" + n
for image in images:
  n = n + 1
  with open ("anime" + str(n) + '.jpg','wb') as f:
    im = requests.get(image)
    f.write(im.content)

版权 (c) 2021,zumbynsr 保留所有权利。

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