banner



How To Code A Discord Bot In C

If you are familiar with online communities and if you are a part of one or you own one, you must have heard near discord and in discord, you may accept seen bots managing those communities. So in this article, we are going to fix our discord developer portal account and will create a discord bot. A minimal bot with basic functionalities and if you want yous can always extend the functionalities of this bot according to your needs.

What is Discord?

Discord is a costless chat app that provides different chat functionalities such as voice, video, and text chat it is used by millions of people around the world for professional as well as fun use.

People create communities referred to as servers in discord and other people can join these servers to hangout at that place to meet new people and talk about their interests. Discord also offers functionality to create private servers where only invited people can bring together using these private servers people can have a individual talk with their close ones.

Discord Servers are filled with channels created by the owner they can be text channels, audio or video channel. These channels are used to talk near specific topics on the server.

What are Discord Bots?

Discord is used past more than 10 million people daily using these stats we can clearly run across people's interest in communities and discord is growing. People are exploring and joining new servers.

Equally the popularity of servers grows people tend to join that server more once the number of members grows it becomes hard for admins to manage the server this is where bots come up into play. There are several tasks admin bots can perform to heighten the user experience on the server. Some of these tasks are

  • Welcoming new members.
  • Answering frequently asked questions.
  • Banning toxic people from servers.
  • Replying, sending, deleting messages.
  • Managing people'south roles in server.

And the list goes on. Admins of huge discord communities always adopt enabling multiple bots on their server, subsequently post-obit this tutorial you tin also create your own discord bot, allow's get started.

Creating a Discord Server

First and foremost we need to have a dedicated server where we are going to setup our bot. This bot will work on a unmarried aqueduct on this server. To create a server you demand to have a discord account if you don't have one still yous can create one by only going to https://discord.com/.

Pace 1: Click on add together server (plus) button on the left sidebar this will open create server interface. Choose the template of your server.

Creating a Server

Step 2: Choose if you using this server for fun or community.

Additional server info

Pace 3: Choose a proficient and catchy proper name for your server if you are using this for the customs you tin simply give the name of your community or business concern.

Name of Server

Step 4: You Server is now created

Server Created

Creating a Channel on Server

Now we need to create a channel where this bot will be active, this bot volition only reply on this channel.

Step ane: Click on add in text channels list.

Creating a channel

Pace 2: Choose the type of aqueduct as a text channel and give your aqueduct a name

Aqueduct Proper name and type

Step iii: Channel is created

Aqueduct Created

But hey, did y'all know that GeeksforGeeks as well has its own Discord server?
No? Well, your day simply got a lot better! Click here to bring together the always-growing tech customs and exist a office of GEEK ARMY!!!

Creating A Bot

At present that we have our account with the server ready we can go alee and create our commencement bot on the discord developer portal. The discord developer portal is a platform provided by discord for people who wants to extend the capabilities of discord and utilise information technology for building more cool stuff, i of the examples is creating bots.

Footstep 1: Login in Portal: Get to https://discord.com/developers/applications and login with your discord business relationship in which the server you desire to build a bot for is created.

Login with Discord account

Step 2: Application refers to new functionality. For example, Bot. Click on new Application to initialize your first bot, choose a proper name for your application. Retrieve the name of the application will be the proper noun of your bot.

Create An Application

Stride 3: Creating a Bot click on Bot in the left sidebar and click on Add together Bot.

Add a Bot

Step four: A popup volition open which will ask you if you lot actually want to add together a bot click on Yes, Do information technology.

Verify you want to add bot

Step v: Copy the token with the COPY button given below this token is used to qualify programs with discord.

Annotation: Never Share your token with everyone!

Copy Auth Token

Customizing and Authorizing Bot

Our bot is created it's time to give permissions and define scopes of the bot. Permission refers to what our bot tin do on the server, for case, sending messages. Scope refers to what office the bot will perform.

Step 1: Click on OAuth2 and click on URL Generator yous will see multiple checkboxes referring to unlike scopes. For this bot, we are going to use bot only telescopic click on Bot checkbox.

Scopes of Bot

Step 2: Adjacent checkboxes are permission for our box. We are going to requite this bot permission to transport and reply to messages then check all the boxes related to that. You lot can always change these permissions later and generate a new URL.

Annotation: If you want to lawmaking slash commands, make sure to cull applications.commands too in Stride 1.

Give Permissions to bot

Step 3: Scroll downwards and you can see a URL generated for the bot click on the copy to copy this URL.

generated URL

Step four: Paste copied URL in a new tab here we are going to authorize our bot with the server. Choose the server we created earlier and click on continue.

Give Server name

Pace 5: Here you will come across the permissions of the bot. If you lot desire you can edit these, click on Authorise

Manage Permissions

Step half-dozen: Verify that you are a homo with a captcha and the bot should be authorized at present.

Verify Captcha

Step 7: Become to the server and you can see the proper name of the bot appearing in the listing of offline people.

Bot appearing in Server

Writing Code for Bot

In this department, we are going to write python lawmaking for our discord bot.

Step 1: We are going to create .env file to store the renewal central for our bot we copied above, .env file will protect our credentials when nosotros will host our lawmaking somewhere. First, create a .env named file in your project folder and then insert the post-obit lawmaking.

TOKEN = '<YOUR_KEY>'

Step 2: Importing modules

Create a new python file for main bot lawmaking and name information technology as yous want and import necessary modules.

  • discord: Library provided by discord for using feature-rich discord API.
  • bone: Nosotros are using environment variables os module is used for importing those.
  • random: Used for performing diverse random operations on information.
  • dotenv: importing .env file into main python file.

Python3

import discord

import os

import random

from dotenv import load_dotenv

Footstep 3: Initializing Variables

Python3

load_dotenv()

client = discord.Bot()

token = os.getenv( 'TOKEN' )

Using load_dotenv() function to import environs variables. Creating discord customer to send a request to discord API and last we are getting and initializing our environment variable token.

Footstep 4: Initializing our Bot

Python3

@customer .consequence

async def on_ready():

print ( "Logged in every bit a bot {0.user}" . format (client))

Here we are using on_ready() result provided past discord API in one case our API client has initialized this event will trigger performing the given performance. Here nosotros are press the proper noun of our bot.

Step 5: Setting upward bot responses

  • We are setting appropriate bot responses to user messages. Discord API consequence on_message which takes an argument as the bulletin is used for this purpose, message argument contains details near the message, author of the message, on which channel the message has been sent .etc
  • Outset excerpt information about the message such as username, channel, and content of the message.
  • The next line plays an of import role if the message is sent by the bot itself then don't reply to information technology if this condition is not written and so the bot will infinitely respond to itself.
  • We are going to actuate our bot on the aqueduct we create in our server called random, yous tin can also actuate the bot in other channels. Writing multiple if-else statements will practice work but you can also implement a chatbot using machine learning. Here we implemented a few if-else statements to respond to basic letters such every bit hi, howdy, and bye and implemented a bones statement to tell a joke. You tin can ever add more functionality and brand your bot more interactable.

Python3

@client .event

async def on_message(bulletin):

username = str (message.author).split( "#" )[ 0 ]

channel = str (message.aqueduct.name)

user_message = str (bulletin.content)

print (f 'Message {user_message} by {username} on {channel}' )

if message.author = = client.user:

render

if channel = = "random" :

if user_message.lower() = = "hello" or user_message.lower() = = "hi" :

await message.channel.send(f 'Hullo {username}' )

return

elif user_message.lower() = = "bye" :

await message.channel.send(f 'Cheerio {username}' )

elif user_message.lower() = = "tell me a joke" :

jokes = [" Tin can someone please shed more than\

light on how my lamp got stolen?",

"Why is she called llene? She\

stands on equal legs.",

"What do you lot call a gazelle in a \

lions territory? Denzel."]

wait message.aqueduct.ship(random.option(jokes))

Stride half dozen: Running bot

Nosotros created the API customer above which provides a office chosen to run this function takes the argument auth token as an argument and runs the bot by calling on_ready event.

Python3

Output:

Bot responding to User letters

Log:

Log of output

Creating Commands

In the above steps, We saw how to employ client.consequence for commands only for practical uses we mostly don't apply that. Discord has provided the states another way to create commands and that is by using prefix.

Stride 1: Import commands

Import commands from discord.ext which will help us implement commands.

Python3

from discord.ext import commands

Footstep two: Choose a Prefix

Now, choose a prefix from which the bot should exist activated and listen to commands. This tin can be any symbol, alphabet or fifty-fifty a word. For the sake of simplicity, we will choose "!" as our prefix. For this edit the previously defined customer:

Python3

client = commands.Bot(command_prefix = "! * )

Step 3: Creating Commands

Now, we will create a command. For this, nosotros volition use customer.control as a decorator.

Python3

@client .command()

async def ping(ctx):

await ctx.send( 'Pong!' )

  • ctx: Represents the commands.context form. This argument is mandatory for all normal commands(Not for slash commands). It represents the context in which a command is beingness invoked nether. This argument can give a lot of meta information for ex,: writer data, message information etc…
  • ctx.ship: This is used to transport the message back to the channel where the control was invoked. Brand certain to use await as this is a coroutine.

At present, run your file again and go the server's aqueduct where the bot is present.
If you type "!ping", The bot volition reply with "Pong".

Decision

And then, this was a basic example to use discord.py library to create a Discord Bot. With the updated version of discord.py even slash commands and Modals can exist created.


Source: https://www.geeksforgeeks.org/building-a-discord-bot-in-python/

0 Response to "How To Code A Discord Bot In C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel