Viewing entries tagged
bot

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

RPi-Logo-Reg-SCREEN.png

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: https://discordapp.com/developers/applications/.

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

newapp.png

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

Click bot.png

4. Click “Add Bot”, and confirm.

Add Bot.png
botconfirm.png

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

token.png

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.

clientid.png

My bot’s client ID is 554549670953615380.

7. Go to https://discordapi.com/permissions.html#3198016, 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.

invitepage.png

8. The invite URL is the one you see towards the bottom. Go to that link in your browser. For my bot, it is: https://discordapp.com/oauth2/authorize?client_id=554549670953615380&scope=bot&permissions=3198016.

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

confirmauth.png

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

joined.png

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

createfile.png

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.

movefile.png
movedfiled.png

5. Navigate back to https://discordapp.com/developers/applications/, and click the application we made earlier.

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

bottokencopy.png

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

droptokeninconffil.png

(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.

copycontents.png

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

        nano config.json
cdtouchnano.png

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

pastenano.png

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

        CTRL+O
        [Enter]
        CTRL+X

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()
                .SetBasePath(AppContext.BaseDirectory)
                .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)
        {
            Console.WriteLine(log.ToString());
            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)
                return;

            if (message.Content == ".hello")
            {
                await message.Channel.SendMessageAsync("world!");
            }  
        }
    }
}
programcseditor.png

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

debugconnected.png

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!)

hellofromlocal.png

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.

gitmod.png

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.

commitmessage.png

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)

gitpull.png

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!

itworks.png
helloworldpi.png

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

RPi-Logo-Reg-SCREEN.png

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: https://dotnet.microsoft.com/download.

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:

dotnethelp.png

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: https://www.raspberrypi.org/documentation/remote-access/ssh/.

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: https://learn.adafruit.com/adafruits-raspberry-pi-lesson-6-using-ssh/ssh-under-windows), 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 ~
wget https://download.visualstudio.microsoft.com/download/pr/35c09285-4114-44f7-aa7d-47fe75a55eda/ac5a8f1bc324f2a6cd021237528441d4/dotnet-sdk-2.2.100-linux-arm.tar.gz
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.

dotnetpi.png

Installing Git

Local Machine

Check out this URL for help installing Git on your local machine: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.

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

git.png

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”.

gitin.png

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

gitpi.png

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: https://code.visualstudio.com.

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.

dotnetnewc.png

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”.

assets.png

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

vscodefolder.png

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
helloworked.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: https://github.com/join?source=header-home. 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.

gitinit.png

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

newfile.png
filename.png

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

        /bin
        /obj
        *.json

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.

contents.png

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

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

6. Now go to Github and login.

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

newrepo.png

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.

create.png

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 https://github.com/gngrninja/csharpi.git                     
            git push -u origin master

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

pushit.png
reposuccess.png

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 https://github.com/gngrninja/csharpi), and click “Clone or download”, and then copy the URL.

copyurl.png

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

        git clone https://github.com/gngrninja/csharpi.git

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

        cd csharpi
        ls
        dotnet run
cdrun.png

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:

helloworldpi.png

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
        
publish.png

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?!)

runpub.png

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 Discord.py

Python: Create a Discord Bot on Your Raspberry Pi Using Discord.py

Create a Discord Bot on Your Raspberry Pi With Python and Discord.py

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

Note
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: https://github.com/gngrninja/blog/tree/master/DiscordBotPi

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

Table of Contents

Note
If you’ve installed Python 3.7, you’ll need the development version of Discord.py. 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)

https://discordapp.com/oauth2/authorize?client_id=your_client_id_goes_here&scope=bot&permissions=0

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

**Note**

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

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
libssl.PNG

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 https://www.python.org/downloads/

wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz

2. Extract the files, and enter the directory

tar xzvf Python-3.6.0.tgz
tar.PNG
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)

./configure

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

make

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 discord.py[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

touch bot.py

    d. Edit the file

nano bot.py

    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)

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


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


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

bot.run(TOKEN)

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

    g. Run your bot!

python3 bot.py

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]