How to Make a Discord Bot with PHP

Building a Discord bot with PHP is completely doable, but it works differently from how most PHP developers expect. There is no web request/response cycle here. Instead, your bot is a long-running CLI process that stays connected to Discord’s gateway over a persistent WebSocket connection.

This guide uses DiscordPHP, the most actively maintained PHP library for the Discord API. It is built on top of ReactPHP and supports the full Discord gateway API, including slash commands, message events, and interactions.

Note: If you are more comfortable with Python or Node.js, those ecosystems have more Discord bot tutorials and community support. PHP is a legitimate choice, but it does have a steeper setup path for this particular task.

how to make discord bot

Prerequisites

Before you start, make sure you have the following:

  • PHP 8.0 or higher running in CLI mode (not FPM or CGI — DiscordPHP will not work on a web server)
  • Composer installed globally (getcomposer.org)
  • A Discord account
  • A server (guild) where you have permission to add bots

What is Discord Bot and Its Uses

Discord bot is the best way to increase the productivity of the server, which helps you to schedule events, sending notifications, get important data, and many more. This is one of the most promising features of Discord, which is used frequently.

Basically Discord bots are automated tasks, which performed on your discord server after specific events occurring. Like sending a welcome message to new members, server moderation, view information about your server or member, leveling system of discord room.

Now talking about how to use these bots, First thing you have to decide what functionality you want on your server. For example, you want to add a flare on the server or need a moderation bot, etc. Many readymade discord bots are available on the internet, a recommended website is top.gg. Here you can find many categorized discord bot, just invite it on your server.

How to Make a Discord Bot with PHP (Step by Step)

Step 1: Create Your Bot Application in the Discord Developer Portal

Every Discord bot starts as an application in Discord’s developer portal. This gives you the bot token your PHP code needs to authenticate.

a. First visit to the discord developer portal. Here you need to create New Application, just name it as you want to identify.

discord developer account

b. Now you get the Client ID and Secret key, note it down, we need it later. Make sure that do not reveal these keys to anyone, otherwise your bot will be hacked.

custom discord bot keys

c. Now add a bot user to your application, via click on the ‘Add Bot’ button. This action is irrevocable so choose wisely.

add discord bot

d. After adding bot user, you got the token, click to reveal token and note it down. This is important, so don’t share it with anyone. Enable PUBLIC BOT option, so this bot can be added by anyone, Or you can keep this bot private.

get bot token

At the same screen below, all the bot permissions are mentioned, you can select any one as per your discord bot requirement.

custom bot permissions

Security warning: Your bot token is equivalent to a password. Never commit it to a public repository, never share it, and never hardcode it directly in your source files. Use an environment variable or a config file excluded from version control.

The above process is for creating a discord bot online via browser app, next we are showing to create custom code for the bot to add more functionality in it and install on your server. So let’s start coding for that..

Step 2: Install DiscordPHP via Composer

Create a new directory for your project and run:

composer require team-reflex/discord-php

This installs DiscordPHP and its dependencies (including ReactPHP). Your project directory should now contain a vendor/ folder and a composer.json.

Optionally, for a faster event loop (recommended for production), install one of these PHP extensions:

# On Ubuntu/Debian, one of:
sudo apt-get install php-uv
sudo apt-get install php-event

These are not required to get started, but they improve performance under load.

Step 3: Write Your First Bot Script

Create a file called bot.php in your project root.

<?php

use Discord\Discord;
use Discord\Parts\Channel\Message;
use Discord\WebSockets\Event;
use Discord\WebSockets\Intents;

include __DIR__ . '/vendor/autoload.php';

$discord = new Discord([
    'token'   => getenv('DISCORD_BOT_TOKEN'), // Load from environment variable
    'intents' => Intents::getDefaultIntents() | Intents::MESSAGE_CONTENT,
]);

$discord->on('ready', function (Discord $discord) {
    echo "Bot is ready!" . PHP_EOL;

    $discord->on(Event::MESSAGE_CREATE, function (Message $message, Discord $discord) {
        // Ignore messages sent by bots (including this bot itself)
        if ($message->author->bot) {
            return;
        }

        if ($message->content === '!ping') {
            $message->channel->sendMessage('Pong!');
        }
    });
});

$discord->run();

What this code does:

  • Intents::getDefaultIntents() | Intents::MESSAGE_CONTENT – enables all default, non-privileged intents plus the Message Content privileged intent. Without MESSAGE_CONTENT, $message->content will be an empty string in guild channels.
  • $discord->on('ready', ...) – all gateway event listeners must be registered inside the ready event, which fires once when the bot connects successfully.
  • $discord->on(Event::MESSAGE_CREATE, ...) – fires every time a message is sent in a channel the bot can see.
  • $message->author->bot check — always filter out bot messages to avoid your bot responding to itself or other bots, which can cause infinite loops.
  • $discord->run() – starts the ReactPHP event loop. This call blocks; code placed after it will not execute until the loop stops.

Step 4: Run the Bot

Set your bot token as an environment variable and run the script from the terminal:

DISCORD_BOT_TOKEN=your-actual-token-here php bot.php

You should see Bot is ready! in the terminal. Go to the Discord server, type !ping in any channel the bot can see, and it should reply with Pong!.

To stop the bot, press Ctrl + C.

Keeping the Bot Running

Running php bot.php in a terminal works for development, but the process will stop when you close the terminal. For a persistent deployment, you have a few options:

Using nohup (simple, not recommended for production):

nohup DISCORD_BOT_TOKEN=your-token php bot.php &

Using a process manager like Supervisor (recommended):

Install Supervisor and create a config file at /etc/supervisor/conf.d/discord-bot.conf:

[program:discord-bot]
command=php /path/to/your/bot.php
environment=DISCORD_BOT_TOKEN="your-token"
autostart=true
autorestart=true
stderr_logfile=/var/log/discord-bot.err.log
stdout_logfile=/var/log/discord-bot.out.log

Then run:

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start discord-bot

Supervisor will automatically restart the bot if it crashes.

Common Errors and Troubleshooting

message->content is always empty You need to enable the Message Content privileged intent both in the Discord Developer Portal (under your bot settings → Privileged Gateway Intents) and in your PHP code by passing Intents::MESSAGE_CONTENT as shown in Step 5.

Class 'Discord\Discord' not found You have not included the Composer autoloader. Make sure include __DIR__ . '/vendor/autoload.php'; is at the top of your script, and that you ran composer require team-reflex/discord-php successfully.

Fatal error: Out of memory DiscordPHP caches a lot of data. If you’re hitting memory limits, add this near the top of your script:

ini_set('memory_limit', '-1');

Use this carefully, unlimited memory is fine for a bot on a dedicated server but should be understood for what it is.

Bot appears online but does not respond Check that the bot has Read Messages/View Channels and Send Messages permissions in the channel you’re testing in. Also confirm the bot is actually in the server and the correct token is being used.

DiscordPHP will only run in CLI You are trying to run the bot via a web server (Apache/nginx/FPM). DiscordPHP cannot run in a web server context, it must run via the PHP CLI. Log into your server via SSH and run it from the command line.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *