A template that I often use when making Discord BOT in Python (memorial note)

Premise

environment


Python 3.6.6
Discord.py-1.2.5

Directory structure


├ cogs
│   └ mainCmd.py
└ main.py

code

main.py


import discord
from discord.ext import commands
import traceback 

DiscordBot_Cogs = [
    'cogs.mainCmd'
]

class MyBot(commands.Bot):
    def __init__(self, command_prefix):
        super().__init__(command_prefix)
        for cog in DiscordBot_Cogs:
            try:
                self.load_extension(cog)
            except Exception:
                traceback.print_exc()

    async def on_ready(self):
        print('BOT start')

if __name__ == '__main__':
    bot = MyBot(command_prefix='!?')
    bot.run('TOKEN') 

mainCmd.py


from discord.ext import commands

class MainCmdCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def cmd(self, ctx):
        await ctx.send("Received a command.")

def setup(bot):
    bot.add_cog(MainCmdCog(bot))

Description and notes

main.py

DiscordBot_Cogs = [
    'cogs.mainCmd'
]

Put 'cogs.mainCmd' in the list DiscordBot_Cogs. When adding a Python file (cog) for commands, follow the list writing method.

DiscordBot_Cogs = [
    'cogs.mainCmd',
    'cogs.exampleCmd'
]

And. cogs is the folder name and mainCmd is the file name without the extension.

for cog in DiscordBot_Cogs:
    try:
        self.load_extension(cog)
    except Exception:
        traceback.print_exc()

Turn the previous list with a for statement and use try & except to register the cog. (An error will occur if the file does not exist because the file name is incorrect.)

if __name__ == '__main__':
    bot = MyBot(command_prefix='!?')
    bot.run('TOKEN') 

Characters to be added to the head with BOT commands (!? In MonsterBOT, / in Minecraft style) mainCmd.py

@commands.command()
async def cmd(self, ctx):
    await ctx.send("Received a command.")

Just type !? cmd and I received thecommand on that channel. A command to send toand BOT.

When using an argument for this, do as follows.

@commands.command()
async def cmd(self, ctx, *args):
    if len(args) == 0:
        await ctx.send("There are no arguments.")
    if len(args) == 1:
        await ctx.send("With one argument**" + args[0] + "**Is.")
    if len(args) == 2:
        await ctx.send("With two arguments**" + args[0] + "**When**" + args[1] + "**Is.")

The rest should be increased.

Recommended Posts

A template that I often use when making Discord BOT in Python (memorial note)
I made a Discord bot in Python that translates when it reacts
Features of regular expression modules that I often use personally in Python
A memo that I wrote a quicksort in Python
[Question] What happens when I use% in python?
In Python, I made a LINE Bot that sends pollen information from location information.
String manipulation with python & pandas that I often use
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
Use communicate () when receiving output in a Python subprocess
Create a discord bot that notifies unilaterally with python (use only requests and json)
I made a discord bot
python Condition extraction from a list that I often forget
[python] A note when trying to use numpy with Cython
Use a macro that runs when saving python with vscode
I tried "a program that removes duplicate statements in Python"
When I made a Discord Bot, my classmates destroyed my computer
A memorandum that you will often use in Python's Selenium
A story that went missing when I specified a path starting with a tilde (~) in python open
[Python] I made a Line bot that randomly asks English words.
I want to use a wildcard that I want to shell with Python remove
Use networkx, a library that handles graphs in python (Part 2: Tutorial)
Easy! Implement a Twitter bot that runs on Heroku in Python
A note I was addicted to when making a beep on Linux
I get a can't set attribute when using @property in python
A story that didn't work when I tried to log in with the Python requests module
When writing a program in Python
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I created a template for a Python project that can be used universally
[Python] I made a decorator that doesn't seem to have any use.
A story about a beginner making a VTuber notification bot from scratch in Python
I made a web application in Python that converts Markdown to HTML
I tried to develop a Formatter that outputs Python logs in JSON
A memorandum because I stumbled on trying to use MeCab in Python
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
A note I looked up to make a command line tool in Python
A useful note when using Python for the first time in a while
Use print in a Python2 lambda expression
I made a payroll program in Python!
Precautions when pickling a function in python
I created a password tool in Python.
A memo that I stumbled upon when doing a quote RT on Twitter Bot
[Complete memorandum] A collection of codes that I often use but cannot remember
I tried to create a class that can easily serialize Json in Python
I made a Line Bot that uses Python to retrieve unread Gmail emails!
I want to create a priority queue that can be updated in Python (2.7)
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
[Beginner] What happens if I write a program that runs in php in Python?
Note that I understand the least squares algorithm. And I wrote it in Python.
I get a strange window when I use the open directory dialog in Tkinter
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I made a familiar function that can be used in statistics with Python
I tried to make a translation BOT that works on Discord using googletrans
A note I was addicted to when running Python with Visual Studio Code
If you want to make a discord bot with python, let's use a framework
A story that I was addicted to when I made SFTP communication with python
I want to create a window in Python
I tried playing a typing game in Python
When I try matplotlib in Python, it says'cairo.Context'
I wrote a class in Python3 and Java
A program that removes duplicate statements in Python