hhstore / blog

My Tech Blog: about Mojo / Rust / Golang / Python / Kotlin / Flutter / VueJS / Blockchain etc.
https://github.com/hhstore/blog/issues
294 stars 24 forks source link

Discord Bot: #388

Open hhstore opened 2 years ago

hhstore commented 2 years ago

related:

hhstore commented 2 years ago

开发一个 Discord Bot:

需求背景:

  1. 需要对 discord 群已经归档的 channel 的历史消息, 做备份迁移. 备份到 thread 内.
  2. 如果手动迁移, 很繁琐. 考虑写个脚本, 进行批量迁移.
  3. 迁移完成后, 将旧的 channel 删除.

discord 官方API文档:

discord bot 项目:

bot 应用:

项目源码:

踩坑:

  1. discord bot 的 token: 长度 = 72

# 大概是这样的: 在创建应用的时候, 先复制出来. 不是 public key.
MTAxODU1ODQ1MjUxxxxxxxxxxxxxwmBA4.pXn8y_xxxxxxxxxxxxxxxxxxxCi5SNtM
  1. 本地调试时, bot 的代码参数, 要添加 http_proxy 参数. 因为被墙, 要走本地 proxy, 才能访问 discord 的服务.

  2. 如果报错, 提示权限问题. 注意在 bot 应用设置页面, 改一下权限设置, 如下截图.

参考:

踩坑:

hhstore commented 2 years ago

准备工作:

discord bot 应用注册:

  1. 个人discord 账号, 改成开发者模式.
  2. 注册一个 discord 应用:
  3. bot 应用设置:
image
  1. 生成 bot 邀请链接: (用于把 bot 添加到指定群)
image

discord bot 应用添加到目标 discord 群:

image image
hhstore commented 2 years ago

基于 Python 开发 Discord Bot:

项目地址:

依赖包:

示例代码:

import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.members = True

# 注意 设置 proxy 参数: 
bot = commands.Bot(command_prefix='$', intents=intents, proxy="http://127.0.0.1:7890")
hhstore commented 2 years ago

discord bot 运行成功的日志:


➤ task discord:run
task: [discord:run] python3 run2.py \
  --token=${DISCORD_TOKEN}
discord token: xxxxxx.xxxxx.xxxxx
2022-09-12 01:50:28 INFO     discord.client logging in using static token
2022-09-12 01:50:33 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: aaefcca2f142ab82e720c10cxxxxxx).
Logged in as
DisMate
101855845252xxxxx791
------
2022-09-12 02:05:41 INFO     discord.gateway Shard ID None has successfully RESUMED session aaefcca2f142ab82e720c10cxxxxxx.

$greet
image
hhstore commented 2 years ago

discord bot 部署说明:

本地调试:

本地部署:

公网部署:

hhstore commented 2 years ago

1

hhstore commented 2 years ago

1

hhstore commented 2 years ago

1