I have recently been working on a python project with programming a discord bot. First I will post my Main.py file, then the error I was having:
import configparser
import os
import discord
from discord.ext import commands, tasks
from discord.ext.commands import bot
import asyncio
#array to send messages to minetest from discord
minetest_messages = []
config = configparser.ConfigParser()
#you may need to path to bot.conf
config.read('bot.conf')
#settings
bot = commands.Bot(
command_prefix=config["BOT"]["command_prefix"],
help_command=None,
intents=discord.Intents(messages=True, message_content=True)
)
lua_file = config["RELAY"]["lua_file_path"]
python_file = config["RELAY"]["python_file_path"]
python_report_file = config["RELAY"]["report_file_path"]
relay_channel = config["RELAY"]["relay_channel"]
report_channel = config["RELAY"]["report_channel"]
cooldown = config["RELAY"]["cooldown"]
debug_channel = config["RELAY"]["debug_channel"]
debug_file = config["RELAY"]["debug_action_file_path"]
def get_reports_msg():
if os.path.getsize(python_report_file) != 0:
messages = []
with open(python_report_file, 'r') as filehandle:
for message in filehandle:
messages.append(message)
#configs.append(currentPlace)
#once readed empty file's input
file = open(python_report_file, 'w')
file.write("")
file.close()
return messages
def get_messages():
#check if file has input or is empty
if os.path.getsize(lua_file) != 0:
messages = []
with open(lua_file, 'r') as filehandle:
for message in filehandle:
messages.append(message)
#configs.append(currentPlace)
#once readed empty file's input
file = open(lua_file, 'w')
file.write("")
file.close()
return messages
def get_debug_message():
#check if file has input or is empty
if os.path.getsize(debug_file) != 0:
messages = []
with open(debug_file, 'r') as filehandle:
for message in filehandle:
messages.append(message)
#configs.append(currentPlace)
#once readed empty file's input
file = open(debug_file, 'w')
file.write("")
file.close()
return messages
def write_messages():
#check if discord has messages to send and if so empty the array and send
if os.path.getsize(python_file) == 0:
#once readed empty file's input
file = open(python_file, 'a')
for dmsg in (minetest_messages):
file.write("{} \n".format(dmsg))
file.close()
minetest_messages.clear()
@bot.event
async def on_ready():
print('Connected!')
#start the loop
task_loop.start()
#fetch messages in the channel
@bot.event
async def on_message(message):
#make sure the channel is the right one and the bot messages getting ignored
if (message.channel.id == int(relay_channel)) and (message.author.id != bot.user.id):
author = message.author.name
if config["RELAY"]["use_nicknames"] == True:
author = message.author.display_name
msg = "[Discord] <{}> {}".format(author, message.content)
minetest_messages.append(msg)
#loop to check if file has input or not
@tasks.loop(seconds=int(cooldown))
async def task_loop():
#incase of an timeout
try:
channel = await bot.fetch_channel(relay_channel)
rep_channel = await bot.fetch_channel(report_channel)
deb_channel = await bot.fetch_channel(debug_channel)
except discord.HTTPException as e:
print(f'Error: {e}')
await asyncio.sleep(60)
#check if channel exists
if channel is None:
print("Error: Channel id {}, dosn't exists".format(channel))
elif rep_channel is None:
print("Error: Channel id {}, dosn't exists".format(rep_channel))
elif debug_channel is None:
print("Error: Channel id {}, dosn't exists".format(debug_channel))
#get messages from lua.txt
messages = get_messages()
report_msg = get_reports_msg()
debug_msg = get_debug_message()
#Read / send messages
if messages != None:
for msg in (messages):
await channel.send(msg)
if report_msg != None:
for rmsg in (report_msg):
await rep_channel.send(rmsg)
if debug_msg != None:
for dmsg in (debug_msg):
await deb_channel.send(dmsg)
#only write if array isn't emtpy
if len(minetest_messages) != 0:
write_messages()
#bot token to run
bot.run(config["TutorialBot"]["MTEyOTM4MDQ2OTU3ODkyNDEwMw.GL2azN.BI1Q54MHF8HnCdf-y5D3cVyEo-l-4vTRCQNvqs"])
I am running up against 1 error that I need a little help resolving (see the following):
Traceback (most recent call last):
File "/home/<user>/Downloads/discordmt_bot-main/Main.py", line 154, in <module>
bot.run(config["TutorialBot"]["<discord account key combination here"])
File "/usr/lib/python3.9/configparser.py", line 960, in __getitem__
raise KeyError(key)
KeyError: 'TutorialBot'
I can provide some of the external files if necessary (this was the only python file) I am inclined to think this error only relates to the python part of the project. Thanks in advance for any assistance!
I am relatively new to python, and have not previously learnt a programming language, so all I knew to do was navigate to my python installation and look in the file that was giving the error, but didn't see anything "out of place".
https://docs.python.org/3/library/configparser.html
Going by the documentation for configparser, seems like you did not write the necessary configurations in bot.conf
.
Python expects this file to follow the format of a .ini
file, which is as follows:
[section1]
key1 = value1
key2 = value2
...
[section2]
...
In this case you are trying to access a section called "TutorialBot
", and from that section, the value of a key named "<discord account key combination here
", which doesn't exist in the bot.conf
file.
It seems like you are trying to configure a token for your discord bot, so here is a solution:
bot.conf:
[Credentials]
Token = TOKEN
Then, to access the value TOKEN
you supply, use config["Credentials"]["Token"]
As you can see, this will look inside the section called "Credentials
", and then access the value of the key called "Token
". Of course, you should substitute TOKEN
with the actual token. You also don't need to use the section/key names that I provided, I was just giving an example.