paint-brush
Creating a Python Discord Bot - How to Get Data for Analysis by@nikagolubeva
6,654 reads
6,654 reads

Creating a Python Discord Bot - How to Get Data for Analysis

by Veronika VasilevaAugust 12th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The ABC cheat sheet for creating a Discord Bot account is simple. Use this article to learn how to: create a Discord bot and add it to the server. Get the full list of channels from the server; get a snapshot of Discord members and their roles. The bot's private password is your private password so don't share it with anybody and use a password manager if necessary. Use the token in the bot's name to create an invite URL for an invite to join a server. The token in this case is necessary.
featured image - Creating a Python Discord Bot - How to Get Data for Analysis
Veronika Vasileva HackerNoon profile picture

Hey!


From this article, you’ll learn how to:


  • create a Discord bot and add it to the Server;
  • get the full list of channels from the server;
  • get a snapshot of Discord members and their roles.

How to Create a Discord Bot Account

Here is a simple ABC cheat sheet for creating a Discord Bot account.


  1. Make sure you’re logged into the Discord website.

  2. Navigate to the application page.

  3. Click the “New Application” button

  4. Name the application and click the “Create” button.


  1. Go to the “Bot” tab and then click “Add Bot”. You’ll have to confirm the action by clicking "Yes, do it!"


Save the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked).

Congrats! Your bot has been created. It was easy, wasn't it?


The next step is to copy the token.


This token is your bot's private password so don't share it with anybody and use a password manager if necessary.


You can regenerate the token in case it is accidentally shared.


  1. On the same page, enable two checkboxes and click the “Save Changes” button.


How to Invite Your Bot to Join a Server

Now you have to get your Bot User into the server. To do this, you should create an invite URL for it.


Go to the "OAuth2" tab. Then select "bot" under the "scopes" section.


Now choose the actions you want to be permitted for the bot. Our bot is going to mainly use text messages so we don't need a lot of permissions.


After selecting the appropriate permissions, click the 'Copy' button below the permissions. This way you'll copy a URL that is  used to add the bot to a server.


Paste the URL into your browser, choose a server to invite the bot to, and click “Continue”.


Сlick “Authorize”. And you’re almost done!


To add the bot, your account needs to have "Manage Server" permissions allowed.

Python Bot

And now…we got to the heart of the matter! Let’s start to create a Bot with Python.


Our main goal here is to get data from Servers and analyze it. You can find more options here: https://discord.com/developers/docs/intro


All the code we need will look like this.


# Import Libraries
import discord
import asyncio
import pandas as pd
from aiohttp import ClientConnectorError
intents = discord.Intents.all()
client = discord.Client(intents=intents)
token = "YOUR_TOKEN"
   

@client.event
async def on_ready():

    # Code to getting data

    await client.close()

try:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.start(token))
except ClientConnectorError:
    print("Discord connection error try again")


Let’s go step by step!


First of all, we’ll try to get a full list of channels.


@client.event
async def on_ready():

    channels_columns = ['channel_id', 'channel_name', 'server_name', 'server_id']
    list_channels = []
    for guild in client.guilds:
        for channel in guild.text_channels:
            try:
                # two lines to check access to the channel
                channelh = client.get_channel(channel.id)
                # trying to get last 10 messages from a channel
                messages = await channelh.history(limit=10).flatten()

                to_append_ch = [channel.id, channel.name, guild.name, guild.id]
                list_channels.append(to_append_ch)
            except discord.Forbidden:  # 403 Forbidden (error code: 50001): Missing Access
                print(f'channel {channel.name} has no access')
                continue

    df_channels = pd.DataFrame(list_channels, columns=channels_columns)
    print(df_channels)
    await client.close()


We need these two lines to check if we have access to the channel.  If your Bot doesn't have access to any channel, these lines return error “403 Forbidden (error code: 50001): Missing Access” and we should print the channel’s name. If you need a full channel list, just delete these lines:


channelh = client.get_channel(channel.id)

messages = await channelh.history(limit=10).flatten()


Let’s add code to get members’ info.


@client.event
async def on_ready():

    channels_columns = ['channel_id', 'channel_name', 'server_name', 'server_id']
    memders_columns = ['member_id', 'name', 'discriminator', 'joined_at',
                       'server_name', 'server_id']
    list_channels = []
    list_memders = []
    for guild in client.guilds:
        for channel in guild.text_channels:
            try:
                # two lines to check access to the channel
                channelh = client.get_channel(channel.id)
                # trying to get last 10 messages from a channel
                messages = await channelh.history(limit=10).flatten()

                to_append_ch = [channel.id, channel.name, guild.name, guild.id]
                list_channels.append(to_append_ch)
            except discord.Forbidden:  
                # 403 Forbidden (error code: 50001): Missing Access
                print(f'channel {channel.name} has no access')
                continue

        for member in guild.members:
            if not member.bot:

                to_append_mem = [str(member.id), member.name,
                                 member.discriminator, member.joined_at, 
                                 guild.name, guild.id]
                list_memders.append(to_append_mem)

    df_channels = pd.DataFrame(list_channels, columns=channels_columns)
    print(df_channels)
    df_memders = pd.DataFrame(list_memders, columns=memders_columns)
    print(df_memders)

    await client.close()


For each user, we get a list of roles that a member has:


# Import Libraries
import discord
import asyncio
import pandas as pd
from aiohttp import ClientConnectorError
intents = discord.Intents.all()
client = discord.Client(intents=intents)
token = "YOUR_TOKEN"

@client.event
async def on_ready():

    channels_columns = ['channel_id', 'channel_name', 'server_name', 'server_id']
    memders_columns = ['member_id', 'name', 'discriminator', 'joined_at',
                       'server_name', 'server_id']
    roles_columns = ['member_id', 'role_id', 'role_name', 'server_name', 'server_id']
    list_channels = []
    list_memders = []
    list_roles = []
    for guild in client.guilds:
        for channel in guild.text_channels:
            try:
                # two lines to check access to the channel
                channelh = client.get_channel(channel.id)
                # trying to get last 10 messages from a channel
                messages = await channelh.history(limit=10).flatten()

                to_append_ch = [channel.id, channel.name, guild.name, guild.id]
                list_channels.append(to_append_ch)
            except discord.Forbidden:  
                # 403 Forbidden (error code: 50001): Missing Access
                print(f'channel {channel.name} has no access')
                continue

        for member in guild.members:
            if not member.bot:
                to_append_mem = [str(member.id), member.name, 
                                 member.discriminator, member.joined_at, 
                                 guild.name, guild.id]
                list_memders.append(to_append_mem)

                us_member = guild.get_member(member.id)
                for us_role in us_member.roles:
                    to_append_rol = [str(member.id), us_role.id, 
                                     us_role.name, guild.name, guild.id]
                    list_roles.append(to_append_rol)


    df_channels = pd.DataFrame(list_channels, columns=channels_columns)
    print(df_channels)
    df_memders = pd.DataFrame(list_memders, columns=memders_columns)
    print(df_memders)
    df_roles = pd.DataFrame(list_roles, columns=roles_columns)
    print(df_roles)

    await client.close()

try:
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.start(token))
except ClientConnectorError:
    print("Discord connection error try again")


So, that’s it! The hardest part is behind us!


And thanks for your attention.


In the next article, we’ll analyze how to get messages and reactions in each server’s channel

See ya’ll!