【问题标题】:Discord bot does not send message to channelDiscord bot 不向频道发送消息
【发布时间】:2021-01-10 00:36:57
【问题描述】:

如果满足某些条件,我正试图让我的机器人向不和谐频道发送消息,但我似乎无法让代码正常工作。代码每 5 秒检查一次列表是否包含字符串“.12”。然后应该转发消息。

import requests
import time
import discord
from discord.ext import commands, tasks
from bs4 import BeautifulSoup

while True:
    client = commands.Bot(command_prefix='.')
    @client.event
    async def on_ready():
        print('bot is active')

    url = 'website link'
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html, 'html.parser')
    html_element = soup.find_all( 'td', { "class" : "eksam-ajad-aeg" } )

    ret = []
    for t in html_element:
        ret.append(t.text)
    print(ret)

    if '.12.' in ret:
        @client.event
        async def send():
            channel = client.get_channel(758088198852182037)
            await channel.send('message')
        client.run('token')
        
    time.sleep(5)

【问题讨论】:

  • 将你的机器人放入while True 似乎有点不寻常。一般情况下,大多数人最后只打一次client.run()。我不确定这是否是您的问题的原因,但我注意到您的机器人有点不寻常。编辑:我想我知道你现在想要做什么。 Asyncio 可能是解决此问题的更好方法:docs.python.org/3/library/asyncio.html 特别是 asyncio.sleep 部分。

标签: python web-scraping discord


【解决方案1】:

这是一个似乎正在运行的机器人脚本。如果没有您尝试搜索的网址,我无法完全提供帮助,但请尝试一下,看看它是否适合您:

import discord
import requests
from bs4 import BeautifulSoup
import asyncio

client = discord.Client()

@client.event
async def on_ready():

    # Create a task and run check_html and feed it a parameter of 5 seconds
    client.loop.create_task(check_html(5))
    print("Bot is active")


async def check_html(time):
    while True:
        url = 'url here'
        res = requests.get(url)
        html = res.text
        soup = BeautifulSoup(html, 'html.parser')
        html_element = soup.find_all( 'td', { "class" : "eksam-ajad-aeg" } )

        ret = []

        for t in html_element:
            ret.append(t.text)
        print(ret)
        if '.12.' in ret:
            for guild in client.guilds:
                for channel in guild.channels:
                    if channel.id == 758088198852182037:
                        await channel.send('message')

        # Asyncronously sleep for 'time' seconds
        await asyncio.sleep(time)

client.run('token')

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2021-03-24
    • 2023-03-07
    • 2020-04-07
    • 2023-03-27
    • 2020-02-07
    • 2020-10-01
    • 2021-05-15
    • 2022-01-21
    相关资源
    最近更新 更多