You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Twitch机器人移植到Discord:实现周期性检测直播并发送消息

解决你的Discord机器人直播检测与代码格式化问题

嘿,刚好我之前折腾过类似的Discord直播通知机器人,来给你唠唠怎么搞定这俩问题!

一、实现定时/独立线程检测直播状态并发送消息

我更推荐用Discord.py自带的tasks模块来做定时检测——它会自动和Discord客户端的事件循环兼容,不用你操心线程安全的问题,比手动开线程省心多了。当然也会给你说下独立线程的实现思路。

方法1:用tasks.loop做定时检测

这是最常用的方案,比如每隔5分钟检测一次服务器所有者的直播状态:

import discord
from discord.ext import tasks, commands

intents = discord.Intents.default()
intents.message_content = True  # 需要在Discord开发者后台开启消息内容权限

bot = commands.Bot(command_prefix='!', intents=intents)

# 定义定时任务,设置每隔300秒(5分钟)运行一次
@tasks.loop(seconds=300)
async def check_stream_status():
    # 获取目标服务器(替换成你的服务器ID)
    guild = bot.get_guild(1234567890)
    if not guild:
        return
    owner = guild.owner
    
    # 调用你之前Twitch机器人的检测逻辑,判断所有者是否在直播
    is_streaming = your_twitch_check_logic(owner.twitch_username)  # 替换成你的检测函数
    
    if is_streaming:
        # 发送通知到指定频道(替换成你的通知频道ID)
        channel = bot.get_channel(9876543210)
        if channel:
            await channel.send(f"🎉 服务器老大{owner.mention}正在Twitch直播啦!传送门:https://twitch.tv/{owner.twitch_username}")

# 机器人就绪后启动定时任务
@bot.event
async def on_ready():
    print(f'已登录:{bot.user}')
    check_stream_status.start()  # 启动定时检测

bot.run('你的机器人TOKEN')

提示:your_twitch_check_logic就是你之前Twitch机器人里调用Twitch API判断直播状态的代码,直接迁移过来就行。

方法2:用独立线程实现检测

如果你一定要用独立线程,得记住Discord的API调用必须在主线程的事件循环里执行——线程里只能做检测逻辑,发送消息要通过loop.call_soon_threadsafe来触发主线程执行:

import discord
import threading
import time
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)

def stream_check_thread():
    while True:
        # 执行直播检测
        guild = bot.get_guild(1234567890)
        if guild:
            owner = guild.owner
            is_streaming = your_twitch_check_logic(owner.twitch_username)
            if is_streaming:
                # 定义发送消息的异步函数
                async def send_notification():
                    channel = bot.get_channel(9876543210)
                    if channel:
                        await channel.send(f"🎉 {owner.mention}开播啦!快冲!")
                # 把发送任务交给主线程的事件循环执行
                bot.loop.call_soon_threadsafe(lambda: bot.loop.create_task(send_notification()))
        time.sleep(300)  # 每隔5分钟检测一次

@bot.event
async def on_ready():
    print(f'已登录:{bot.user}')
    # 启动检测线程(设置daemon=True让线程随主程序退出)
    threading.Thread(target=stream_check_thread, daemon=True).start()

bot.run('你的机器人TOKEN')

这种方式要格外注意线程安全,除非有特殊需求,还是tasks模块更靠谱。

二、正确格式化代码块

其实超简单,用三个连续的反引号(`)包裹代码,还可以指定代码语言(比如python),这样不管是Markdown编辑器还是Stack Overflow都会自动高亮代码:

# 这是一个Python代码块示例
def greet():
    print("Hello, Discord Bot!")

如果是其他语言,比如JavaScript,就写成javascript ... 。要是在Stack Overflow提问,直接点编辑器里的代码块按钮,粘贴代码后选对应的语言就行,比手动打反引号更省事。

内容的提问来源于stack exchange,提问作者Leotomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:59:29