Viewing entries tagged

C# Discord Bot on Raspberry Pi: Simple Bot With Config File

C# Discord Bot on Raspberry Pi: Simple Bot With Config File

CSharPi: Simple Bot With Config File


Now let’s get a Discord bot working on our Pi!

Creating the Discord App

We will need a bot token to authenticate the bot and get things going.

1. Login to the developer portal for Discord, here:

2. Once logged in, click “New Application”, and give it a name.


3. Now click “Bot” on the menu to the left.

Click bot.png

4. Click “Add Bot”, and confirm.

Add Bot.png

5. Now you should see an option to reveal the bot’s token. We will need to get this information shortly.


6. Let’s invite the bot to a Discord server. You will need to be an administrator on the server you want to invite the bot to. To do this, go to the “General Information” option on the menu to the left, and copy the Client ID.


My bot’s client ID is 554549670953615380.

7. Go to, and input your client ID towards the bottom. I’ve added the basic permissions that will be good for this example bot. Feel free to add more if you’d like.


8. The invite URL is the one you see towards the bottom. Go to that link in your browser. For my bot, it is:

9. Confirm the server you are adding the bot to, and click “Authorize”.


10. You should now see an (offline) bot join your server.


Token in Configuration File

Local Machine

From here on out we will be relying upon the groundwork we laid in this post:

If you haven’t done the setup in that post, but are an advanced user familiar with C# / .NET Core, carry on. Otherwise, I strongly recommend going through it.

1. Open the csharpi folder in Visual Studio Code on your local machine.

2. Create a new file in the root named config.json


3. Give it the following content:

        "Token":  ""

4. Move the file to the /bin/Debug/netcoreapp2.2 folder
(note) the only reason we are creating this copy is for testing, and when we debug the app it uses this folder as its root folder. We will be creating a separate config.json on the Pi in a moment.


5. Navigate back to, and click the application we made earlier.

6. Click “Bot from the menu on the left, and then click “Reveal Token


7. Copy the token and drop it inbetween the quotes in the config.json file.


(note) it is very important you keep your token a secret, and regenerate it if you think anyone else knows it.

Raspberry Pi

1. SSH into your Raspberry Pi

2. Navigate to the published folder we created in part one:

        cd /home/pi/bot

3. Create the configuration file here:

        touch config.json

4. Copy the contents of the file from the one created on your local machine.


5. Open the config.json file in /home/pi/bot on the Pi in nano:

        nano config.json

6. Once the editor is opened, paste in the contents.


7. Use the following sequence to write the contents and exit the editor:


8. Verify the file contents via the more command:

        more config.json
Screen Shot 2019-03-11 at 12.18.17 AM.png

Add Required Packages

Now it is time to add required packages to our project. We will need to add the Discord.Net package, and a couple Microsoft configuration packages to help us read and store the configuration file.

1. Open your favorite console / terminal, and navigate to the csharpi project folder on your local machine.

2. Run the following commands:

dotnet add package Discord.Net --version 2.0.1
dotnet add package Microsoft.Extensions.Configuration --version 3.0.0-preview3.19153.1   
dotnet add package Microsoft.Extensions.Configuration.Json --version 3.0.0-preview3.19153.1

Add Simple Bot Code

Now we’re going to replace the contents of Program.cs with the simple bot code. This code will be the basis for future posts to come.

1. Open the csharpi folder on your local machine in Visual Studio Code.

2. Replace the contents of Program.cs with the following:
(note) If you did not name your project csharpi, be mindful of the namespace declaration and update yours to match your project name!

using System;
using Discord;
using Discord.Net;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace csharpi
    class Program
        private readonly DiscordSocketClient _client;
        private readonly IConfiguration _config;

        static void Main(string[] args)
            new Program().MainAsync().GetAwaiter().GetResult();

        public Program()
            _client = new DiscordSocketClient();

            //Hook into log event and write it out to the console
            _client.Log += LogAsync;

            //Hook into the client ready event
            _client.Ready += ReadyAsync;

            //Hook into the message received event, this is how we handle the hello world example
            _client.MessageReceived += MessageReceivedAsync;

            //Create the configuration
            var _builder = new ConfigurationBuilder()
                .AddJsonFile(path: "config.json");            
            _config = _builder.Build();

        public async Task MainAsync()
            //This is where we get the Token value from the configuration file
            await _client.LoginAsync(TokenType.Bot, _config["Token"]);
            await _client.StartAsync();

            // Block the program until it is closed.
            await Task.Delay(-1);

        private Task LogAsync(LogMessage log)
            return Task.CompletedTask;

        private Task ReadyAsync()
            Console.WriteLine($"Connected as -> [{_client.CurrentUser}] :)");
            return Task.CompletedTask;

        //I wonder if there's a better way to handle commands (spoiler: there is :))
        private async Task MessageReceivedAsync(SocketMessage message)
            //This ensures we don't loop things by responding to ourselves (as the bot)
            if (message.Author.Id == _client.CurrentUser.Id)

            if (message.Content == ".hello")
                await message.Channel.SendMessageAsync("world!");

3. Now that we have the new code for Program.cs, let’s test it by debugging (F5).


4. Now that we verified it is connected and debugging, try sending .hello to the discord server your bot is in, and see what happens (the bot should appear online now!)


Awesome! It works locally. Now let’s work on getting it to the Pi.

Commit New Code to Github

Let’s get our new code committed to Github!

1. Open up the csharpi folder on your local machine with VS Code.

2. The Git icon should show that 2 files have been modified. These are the .csproj file with the required packages we added, and the Program.cs file we modified.


3. Since VS Code is Git-aware, let’s push these changes up to our Github repository.

4. Add a commit message and click the checkmark icon to stage/commit the files.


5. Now click the three dots “”, and select “Push”.

6. Verify the files have been modified by going to your Github repository’s page:

Update Code on Pi

Now let’s get the updated code on the Raspberry Pi, and publish the app again. After we do that, we can run the updated app and ensure it works as the Discord bot!

1. SSH into your Pi.

2. Navigate to the source code folder /home/pi/csharpi:

    cd /home/pi/csharpi

3. Run:

    git pull

(you should see that some changes have been made)


4. Now let’s publish and run the application (since we already created config.json in /home/pi/bot earlier, it should pick up that file and have the token ready). The first command publishes the application, then we change directory to the published application, and run it.

dotnet publish -o /home/pi/bot
cd /home/pi/bot
dotnet csharpi.dll

(note) The restore/publishing process will take a while, but you only need to run it if your code has changed.

If all goes well, we should see our bot connected message, and we can test it out in the Discord server!


And there you have it, a Discord bot running on a Raspberry Pi, with .NET Core and C#. The next parts of this series will go over proper command handling (hint: not how we did it here), and more!

C# Discord Bot Series

Next post:

If you have any feedback or questions, feel free to leave a comment below!

C# Discord Bot on Raspberry Pi: Setting Things Up

C# Discord Bot on Raspberry Pi: Setting Things Up

CSharPi: Getting Started


What if I said it was possible to run a Discord bot on a Raspberry Pi natively? With .NET Core we can do just that.

Getting Started

Let’s get some prerequisites out of the way. The first thing we’ll do is install the .NET Core SDK on our local machine, as well as our Raspberry Pi. Next, we’ll ensure Git is installed both places as well.

Finally, I will be using Visual Studio Code for this project, so I will go over installing that as well.

If you are familiar with all of these concepts, and have created Discord bots before, feel free to skip to the next part of the series:

Otherwise, carry on!

Installing .NET Core

Local Machine

Let’s start out by installing the .NET Core SDK on our local machine. You’ll want to start here, and follow specific instructions for your OS:

Once installed, you can verify it is working by dropping to the command line (OSX you’ll use Terminal, Windows you want PowerShell, and Linux whatever your favorite shell is), and running: dotnet --help

You should see something like this:


Raspberry Pi

The one prerequisite here is that you can SSH into your Raspberry Pi. If you need some help enabling SSH, check out this article here:

If you’d like to setup your Raspberry Pi headless, and ensure it connects to your WiFi network and automatically enables SSH on first boot, check out my post:

Once you’re sshed in (Windows users that need help check this out:, you can start installing .NET Core on your Pi.

The following commands will:

1. Navigate to the home directory

2. Download the .NET Core SDK

3. Create the directory /opt/dotnet

4. Uncompress the archive we downloaded into /opt/dotnet

5. Create a symbolic link so we can use the dotnet command

cd ~
sudo mkdir /opt/dotnet
sudo tar -zxf dotnet-sdk-2.2.100-linux-arm.tar.gz -C /opt/dotnet
sudo ln -s /opt/dotnet/dotnet /usr/local/bin

If all goes well, we should be able to run: dotnet --version.


Installing Git

Local Machine

Check out this URL for help installing Git on your local machine:

We can verify it works after installing by dropping to your favorite shell and running: git.


Raspberry Pi

If you are using the minimal (lite) version of Raspbian, or need Git installed otherwise, run: sudo apt install git, and accept any prompts with “y”.


Now we can run: git to verify it installed correctly.


Visual Studio Code

Visual Studio Code has become my editor of choice, even for some C# projects. We will install the client onto our local machine so we can edit the code there. For help installing Visual Studio Code, go here:

Once you have Visual Studio Code installed, open it up and click the extensions icon on the left (looks like a square). Then search for and install the C# extension. In this screenshot, it is the only one in the list for me that does not have an install option, and has a gear next to it (since I already have it installed). Once you install it, it will give you the option to reload Visual Studio Code.

C# ext.png

Creating the .NET Core Project

Now we will be creating the .NET Core project. The machine we will be doing this on is our local machine, not the Pi.

Hello World

Let’s start by creating a dotnet console application.

1. Fire up your favorite shell, and run: dotnet new console -n csharpi.

This will create a new directory named csharpi, and create the project there.


2. Now open up the csharpi folder with Visual Studio Code. You will see a prompt in the lower right-hand corner asking if you want to add required assets, click “Yes”.


If all went well, you will now see a .vscode folder in the list.


3. Now to test things out. Click Program.cs to see the example code the default project provides that will write out “Hello World” to the console. Go to the Debug menu, and click “Start Debugging” (or simply hit F5).

debut menu.png

If you see “Hello World”, our project has been created, and we have the ability to edit it in Visual Studio Code.

Git Repository Initialization

Now we will initialize the local instance of the Git repository, and push up our code to Github. If you don’t have an account on Github, you can create one, here: Once you create it, log in and hang on because we will be using it shortly.

Local Initialization

1. Open up your favorite terminal / console and navigate to the csharpi folder we created. Once there, run: git init. Keep the window open.


2. Open up the csharpi folder in Visual Studio Code. You’ll notice the Git icon (branching line) has an indicator that there are 22 files to work with. Let’s fix that by creating a file named .gitignore, and tell Git what files we don’t want to commit.

3. Click the File icon in VS Code to see the files in the project, and then click the create new file icon. Name the file .gitignore


4. Open the .gitignore file by clicking it, and add the following contents:


This will tell Git to ignore the /bin and /obj folders, as well as any file ending in .json. Since we will be creating a json configuration file with a token we do not want to share in it later, this is a good thing.


5. Switch back to the terminal / console window you have open and run:

        git add .        
        git commit -m 'first for csharpi'

6. Now go to Github and login.

7. Once logged in, click the [+] icon in the upper right, and select “New repository”.


8. On the next page, give it a name and description. Keep it public to follow along with this tutorial. Cloning it will be much easier on the Pi that way.


9. Click “Create repository, and check out the instructions on the next screen. You’ll see that we completed most of it already.

10. Run the two commands for existing repository.

For me it is (your commands will look similar, with the url after origin reflecting your username and repo name):

            git remote add origin                     
            git push -u origin master

11. You should now see the following on the command line, and on Github once you refresh the page:


Cloning the Repository to the Pi

Now let’s test that .NET Core is working correctly on the Pi.

1. Go to your Github repository for this project (for me it is, and click “Clone or download”, and then copy the URL.


2. SSH into your Raspberry Pi and run git clone, and then paste in the URL we copied from the above step.:

        git clone

3. We can now change directory to csharpi, check out the contents, and try running it (essentially in debug mode):

        cd csharpi
        dotnet run

4. Debugging on the Pi with .NET Core is not fun. It takes forever, and is on their list to fix (as much as they can, considering it is not the fastest processor). Eventually, however, you should see the following:


5. Fret not, running the compiled/published application is much faster. To see this happen let’s create a folder under our home folder that will contain the published version of our code.

        mkdir /home/pi/bot

6. The /home/pi/csharpi folder will contain the code we clone from the repo, that we work on from our main machine via VS Code. The /home/pi/bot folder will contain the published version of that code, that executes much faster. Let’s ensure we are in the source code folder, and run the command to publish the app:

        cd /home/pi/csharpi
        dotnet publish -o /home/pi/bot

7. Now that it is published, we can run the application. It will execute much faster as the published version.

        cd /home/pi/bot
        dotnet csharpi.dll

(I know right, running a dll on *nix?!)


Success! We now have the groundwork laid for creating the Discord bot.

Now let’s get a Discord bot going:

Python: Create a Discord Bot on Your Raspberry Pi Using

Python: Create a Discord Bot on Your Raspberry Pi Using

Create a Discord Bot on Your Raspberry Pi With Python and

This article will get you up and running with a Discord bot on your Raspberry Pi using the Discord.Py library.

The code has been updated to reflect Discord.Py’s re-write.
You can always view latest code, and more examples for this post, here:

This assumes that you've installed and are using Raspbian.

Table of Contents

If you’ve installed Python 3.7, you’ll need the development version of Check out the instructions for installing that over at their developer’s README. It is strongly recommended to stay on 3.6.x, however.

Create app and invite bot to your server

If you already have a bot token, and a bot invited to your server, you can skip over to updating Raspbian.

1. Navigate to the Discord Developer Console

2. Click "New App"

3. Give it a name, and then click "Create App"

4. Click "Create a Bot User"

5. Keep note of the Token, as you'll need that later.

6. Invite the bot to your server

    a. Use the following URL to invite the bot to your server:
        (Replace your_client_id_goes_here with your bot's client ID)

7. You should now see the bot in your server (offline)

Update Raspbian

First you'll want to ensure your Raspbian installation is up to date. To do this, run the following commands:

1. Update package lists

sudo apt-get update

2. Upgrade packages

sudo apt-get upgrade

3. Clean things up

sudo apt-get dist-upgrade

4. Reboot your Pi!

Install Pre-Requisites for Python 3.6.x and Discord.Py


The latest version of Raspbian (9.x/Stretch) ships with Python 3.5.3 (which should work great with 

If you'd like to upgrade your OS to Stretch, follow this article.

To check which version you have, run:

cat /etc/os-release
Screenshot 2018-03-12 at 10.43.55 PM.png

If you are running Stretch, great! Click here to skip to the next step. Otherwise, continue below.

1. Install libssl-dev (to ensure we can use pip when we install the newest version of Python)

sudo apt-get install libssl-dev

2. Install libffi-dev (to ensure audio works with the Discord bot)

sudo apt-get install libffi-dev

3. Install libsqlite3-dev (this will be handy, as it installs libraries needed to install sqlite3 support)

sudo apt-get install libsqlite3-dev

Install Python 3.6.x

1. Grab the latest version of Python 3.x from


2. Extract the files, and enter the directory

tar xzvf Python-3.6.0.tgz
cd Python-3.6.0/

3. Run configure to check for dependencies, and get ready to build the Python installation
(This will take 2-5 minutes)


4. Run make to start compiling the software
(This will take 15-30 minutes)


5. Install Python 3.6.x
(This will take 10-15 minutes)

sudo make install

6. Reboot your Pi!

Install Discory.Py, and get a bot working

1. Install latest version of the Discord library for Python (Discord.Py)

sudo python3 -m pip install -U[voice]

2. Create a bot to test it out

    a. Create directory 

mkdir ~/pipy_bot

    b. Move to that directory

cd ~/pipy_bot

    c. Create an empty file


    d. Edit the file


    e. Copy/Paste the following content in the editor (be sure to change your_token_here to your bot's token):

import discord
from discord.ext import commands

TOKEN = ''

description = '''ninjaBot in Python'''
bot = commands.Bot(command_prefix='?', description=description)

async def on_ready():
    print('Logged in as')

async def hello(ctx):
    """Says world"""
    await ctx.send("world")

async def add(ctx, left : int, right : int):
    """Adds two numbers together."""
    await ctx.send(left + right)

    f. Save the file using CTRL+X, and "y"

    g. Run your bot!


Test Out Your Bot

1. Go to the Discord server where you've invited your bot to , and try issuing the ?help command

2. Once you verified that works, try the other ones as well!

Have a question or idea? Leave a comment below, or contact me here!

[Back to top]