PHP Discord获取频道消息功能实现
- 1. 关注对应频道
- 2. 添加机器人
- 3. 配置机器人权限
- 4. 使用 `DiscordPHP` 类库
- 5. 代码示例 (Laravel 框架)
- 6. 服务器部署
1. 关注对应频道
首先要创建自己的频道, 然后到对应的公告频道中关注这个频道(这时
Discord
会让你选择频道, 选择之前创建的频道就可以了)
2. 添加机器人
https://discord.com/developers/applications
到Discord
开发者地址, 然后创建一个自己的机器人即可
3. 配置机器人权限
进入设置后 选择
OAuth2
然后 选择第一个子选项
如图: 选择bot
,Administrator
选择Bot
,上传头像,填写名称
配置机器人
下面MESSAGE CONTENT INTENT
(重点没有选择的话,后面获取内容都是空的)
4. 使用 DiscordPHP
类库
文档地址 https://packagist.org/packages/team-reflex/discord-php
按照类库composer require team-reflex/discord-php
5. 代码示例 (Laravel 框架)
先在自己的频道发消息, 然后在日志中查看
$message->content
如果为空 (看第三步配置)
<?php
/*** Discord*/use App\Models\DiscordMessage;
use Discord\Discord;
use Discord\Exceptions\IntentException;
use Discord\Parts\Channel\Message;class DiscordUtils
{// 配置public $config = ['token' => 'xxx',];// 频道IDpublic $channelId = 'xxx';// 官方IDpublic $userId = 'xxx';/*** @throws IntentException*/public function __construct(){$this->init();}/*** 初始化* @throws IntentException*/public function init(){$discord = new Discord($this->config);$discord->on('ready', function (Discord $discord) {logger("Bot is ready!");$discord->on('message', function (Message $message, Discord $discord) {// 在这里处理收到的消息 logger("Received Message :" . $message->content);// 这里判断只记录 公告频道的官方发布的消息// 指定频道的$channel = $message->channel_id === $this->channelId;// 指定官方
// $official = $message->user_id == $this->userId;// 消息ID 不为空, 是指定频道, 消息ID是不存在的if ($channel) {$data = ['message_id' => $message->id,'channel_id' => $message->channel_id,'user_id' => $message->user_id,'username' => $message->author->username,'content_en' => $message->content,'content' => $message->content,'timestamp' => $message->timestamp->toDateTimeString(),];logger('write: ', $data);$this->write($data);}});});$discord->run();}/*** @param $data*/public function write($data){try {if (!DiscordMessage::query()->where('message_id', $data['message_id'])->exists()) {logger('写入: ', $data);DiscordMessage::query()->insertGetId($data);} else {// 重复写入logger('Repeat Write Records');}} catch (\Exception $e) {logger('write error');}}
}
6. 服务器部署
命令只执行一次即可, 因为这是一个
Websocket
(不要用定时任务, 否则请求过高会要求更换Token)
<?phpnamespace App\Console\Commands;use App\Library\Api\DiscordUtils;
use Illuminate\Console\Command;class GetDiscordMessage extends Command
{/*** php artisan discord:message >> /dev/null 2>&1* php artisan discord:message --option -d* The name and signature of the console command.** @var string*/protected $signature = 'discord:message';/*** The console command description.** @var string*/protected $description = '获取Discord消息';/*** Create a new command instance.** @return void*/public function __construct(){parent::__construct();}/*** Execute the console command.*/public function handle(){logger('执行 - 获取Discord消息');new DiscordUtils();}
}