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

使用Nextcord/discord.py实现Discord机器人发送.txt随机行

实现Discord机器人从TXT随机读取内容发送

不管用nextcord还是discord.py,核心逻辑都是读取TXT文件内容、随机选取一行、通过机器人命令发送。下面分别给出两种框架的实现方案,代码都是新手友好的:

方案一:使用nextcord

  1. 先安装依赖:
pip install nextcord
  1. 完整代码示例:
import nextcord
from nextcord.ext import commands
import random
import os

# 初始化机器人,设置命令前缀为!
bot = commands.Bot(command_prefix="!", intents=nextcord.Intents.default())

# 机器人上线提示
@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

# 定义随机发送内容的命令
@bot.command(name="randomline")
async def send_random_line(ctx):
    # 替换成你的TXT文件路径,和脚本同目录直接写文件名就行
    txt_path = "content.txt"
    
    # 检查文件是否存在
    if not os.path.exists(txt_path):
        await ctx.send("找不到指定的TXT文件!")
        return
    
    # 读取文件内容,自动过滤空行
    with open(txt_path, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]
    
    # 检查文件是否为空
    if not lines:
        await ctx.send("TXT文件里没有有效内容!")
        return
    
    # 随机选一行发送
    random_line = random.choice(lines)
    await ctx.send(random_line)

# 替换成你自己的机器人Token,不要泄露!
bot.run("YOUR_BOT_TOKEN_HERE")

方案二:使用discord.py

discord.py的逻辑和nextcord几乎一致,只是导入和装饰器略有不同:

  1. 安装依赖:
pip install discord.py
  1. 完整代码示例:
import discord
from discord.ext import commands
import random
import os

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

@bot.command(name="randomline")
async def send_random_line(ctx):
    txt_path = "content.txt"
    
    if not os.path.exists(txt_path):
        await ctx.send("找不到指定的TXT文件!")
        return
    
    with open(txt_path, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]
    
    if not lines:
        await ctx.send("TXT文件里没有有效内容!")
        return
    
    random_line = random.choice(lines)
    await ctx.send(random_line)

bot.run("YOUR_BOT_TOKEN_HERE")

注意事项

  • 把content.txt替换成你自己的文件名,确保文件和脚本在同一目录,或者写完整路径
  • TXT文件里每行放一条要发送的内容,空行会被自动过滤
  • 机器人需要在Discord开发者平台创建,并且邀请到你的服务器(需要发送消息的权限)
  • 绝对不要把你的机器人Token泄露给任何人,泄露后要立刻去开发者平台重置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:40:34