PHP Discord获取频道消息功能实现

8 篇文章 0 订阅

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',
    ];
    // 频道ID
    public $channelId = 'xxx';
    // 官方ID
    public $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. 服务器部署

这里建议使用 进程守护 保持这个命令执行后的进程一直都在
然后在 进程守护 中去管理和重启这个命令(业务逻辑发生修改后需要重启)
注意: 这里不适合使用定时器, 这样会导致服务器或者数据库压力巨大,从而导致宕机

<?php

namespace 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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值