Why is my on_message event printing logs twice? - python

Here is the logging bit of my on_message command, whenever I send "ping" it checks to make sure it's in its list of commands then logs it, but its logging it twice and sending once (It should only send once)...
async def on_message(message):
# Check if the message was from server
if message.content != "":
# Test if User/ Bot
if message.author == bot.user:
return
# Report Comamnd used
else:
splitCommand = message.content.split(" ")
join = " "
join = join.join(splitCommand)
time = "[UTC " + str(message.created_at) + "]"
singleCommand = "\nCommand: \'" + splitCommand[0] + "\'"
multiCommand = "\nCommand: \'" + join + "\'"
user = "\nFrom User: \'<#" + str(message.author.id) + "> | (" + str(message.author) + ")\'"
# Single word commands
if splitCommand[0].lower() in commandList:
print(time + singleCommand + user)
# Multi-word commands
if any(x.isalpha() or x.isspace() for x in join):
if join.lower() in commandList:
print(time + multiCommand + user)
elif regex.search(join) != None and join.lower() in commandList:
print(time + multiCommand + user)
# Deletes Commands
if message.content[0] == prefix:
userMessage = message
await userMessage.delete()
print("Deleted Command")
else:
pass
An example output would be:
[UTC 2020-11-24 08:21:42.587000]
Command: 'ping'
From User: '<#379355817700491264> | (24Kings#0001)'
[UTC 2020-11-24 08:21:42.587000]
Command: 'ping'
From User: '<#379355817700491264> | (24Kings#0001)'
Sent: 'pong'
But it should only be logging it once?
Any ideas as to why it is logging twice and a fix would be very much appreciated! :D

First of all it is better to use discord.ext.commands, After that you have three options.
on_command_error(ctx,error) To check for error and tell the user (permissions, wrong argument, etc..)
on_command(ctx)
on_command_completion(ctx)
#bot.event
async def on_command_completion(ctx):
print(f'{ctx.command} has been used by {ctx.author.display_name}')
For commands here is a ref

Related

Python Dictionary-Bot Questions

I was making a discode dictionary bot. The function I want is for the user to enter a word and the meaning of the word through a command to the bot.
So what's been conceived!It's input (word) (meaning), but the problem is that the bot separates words and their meanings by spaces, so if the meaning gets longer, only the sentence before the space is saved as meaning.
For example, if you type !input anarchism is a~~,
When you print it out, it only outputs up to anarchism.
I think it's because there's a space between the word anarchism and is. Please look at my code and answer me how to fix it.
import discord
from discord.ext import commands
from discord.utils import get
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all())
front_command = "!"
user_input = ""
user_output = ""
check_number = 0
#bot.event
async def on_ready():
print('Logging in..: ')
print(bot.user.name)
print('connection was succesful')
await bot.change_presence(status=discord.Status.online, activity=discord.Game("Testing"))
#bot.command()
async def input(ctx, arg1, arg2):
global check_number
temp_f = open("user.txt","r")
datafile = temp_f.readlines()
if len(datafile) == 0:
temp_f.close()
temp_f = open("user.txt","w")
temp_f.write(ctx.author.name + " " + str(arg1) + " " + str(arg2) +"\n")
await ctx.send("Registration completed!")
else:
for i in range(len(datafile)):
if arg1 in datafile[i]:
temp_f.close()
temp_f = open("user.txt","w")
datafile[i] = ctx.author.name + " " + str(arg1) + " " + str(arg2) +"\n"
temp_f.write('\n'.join(datafile))
await ctx.send("There is aleready "+str(arg1)+" related input, so it is changed to input now!")
check_number = 1
break
if check_number == 0:
temp_f = open("user.txt","w")
temp_f.write(ctx.author.name + " " + str(arg1) + " " + str(arg2) +"\n")
await ctx.send("Registration completed!")
check_number = 0
temp_f.close()
#bot.command()
async def output(ctx, arg1):
global check_number
temp_f = open("user.txt","r")
datafile = temp_f.readlines()
if len(datafile) == 0:
await ctx.channel.send("Nothing's registered yet! :)")
else:
for i in range(len(datafile)):
if arg1 in datafile[i]:
info = datafile[i].split()
msg = await ctx.send(str(info[2]))
await msg.reply(str(info[0]) + " " + "wrote this!")
check_number = 1
break
if check_number == 0:
await ctx.channel.send("Nothing's registered yet! :)")
check_number = 0
bot.run('Token')
I hope I understood your question correctly.
You can add a * before your last argument to get everything the User has written, like this:
#bot.command()
async def input(ctx, arg1, *, arg2):
You could also circumvent it by having the user surround the input in quotes, in your example it would be: !input anarchism "your definition here", but the method above is more user-friendly.

How do you reference a string on a different line in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm doing some code atm which currently does a request and then goes to another channel, and edits a schedule that adds what the person requested, I am currently working to make it so you can set it up in a discord server instead of my current system (referencing specific discord channels for testing) atm the Mondaymsg string etc. aren't being found by the Monday area on my code, and I don't know what to change to get it to reference, I am an on-the-go learner coder so my code may look bad but I hope I can get some help so I can improve.
#bot.command(name='raid', pass_context=True)
async def raid(ctx, arg, arg1 = None, arg2 = None, arg3 = None,*, role_name = None):
if arg == 'setup' :
setupchannel = ctx.channel
ctx.channel.purge(amount=1)
await setupchannel.send("**=====** __**RAID SCHEDULE**__ **=====**")
Mondaymsg = await setupchannel.send("__**Monday**__")
Tuesdaymsg = await setupchannel.send("__**Tuesday**__")
Wednesdaymsg = await setupchannel.send("__**Wednesday**__")
Thursdaymsg = await setupchannel.send("__**Thursday**__")
Fridaymsg = await setupchannel.send("__**Friday**__")
Saturdaymsg = await setupchannel.send("__**Saturday**__")
Sundaymsg = await setupchannel.send("__**Sunday**__")
elif arg == 'add':
if arg1 == 'Monday':
Userping = ctx.author.mention
Message = Mondaymsg()
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
messageContent = Mondaymsg.message.content
if arg3 in str(Mondaymsg.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await Mondaymsg.edit(content=messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Tuesday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879568853045235773)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Wednesday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879569158092783667)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Thursday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879569232336125972)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Friday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879569295313600573)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Saturday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879569379363258438)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
elif arg1 == 'Sunday':
channel = bot.get_channel(879538507905921125)
Userping = ctx.author.mention
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
message = await channel.fetch_message(879569473688973403)
messageContent = message.content
if arg3 in str(message.content):
emoji = '❌'
await ctx.message.add_reaction(emoji)
await ctx.channel.send(Userping + " Your selected time is already taken on this day, please select a different time")
else:
if role in ctx.guild.roles:
emoji = '✅'
await ctx.message.add_reaction(emoji)
await message.edit(content = messageContent + "\n" + Userping + " | " + f"{role.mention}" + " " + arg2 + " | " + arg3)
else:
await ctx.channel.send(Userping + " " + "I'm sorry, you need to input the name of the role you are hosting for (Example: Spectre Platoon, Diablo Squad etc.)")
else:
await ctx.channel.send("I'm sorry, your day input was invalid, please put one of the following days:\n\n"
"*Monday*\n"
"*Tuesday*\n"
"*Wednesday*\n"
"*Thursday*\n"
"*Friday*\n"
"*Saturday*\n"
"*Sunday*"
)
elif arg == 'clear':
channel = bot.get_channel(879538507905921125)
mondaymessage = await channel.fetch_message(879568766365736972)
tuesdaymessage = await channel.fetch_message(879568853045235773)
wednesdaymessage = await channel.fetch_message(879569158092783667)
thursdaymessage = await channel.fetch_message(879569232336125972)
fridaymessage = await channel.fetch_message(879569295313600573)
saturdaymessage = await channel.fetch_message(879569379363258438)
sundaymessage = await channel.fetch_message(879569473688973403)
await mondaymessage.edit(content='**__Monday__**')
await tuesdaymessage.edit(content='**__Tuesday__**')
await wednesdaymessage.edit(content='**__Wednesday__**')
await thursdaymessage.edit(content='**__Thursday__**')
await fridaymessage.edit(content='**__Friday__**')
await saturdaymessage.edit(content='**__Saturday__**')
await sundaymessage.edit(content='**__Sunday__**')
It looks like you're asking why variables defined in the first IF body aren't accessible in other IF bodies:
def func():
if some_condition:
var1 = 'blah'
var2 = 'asdf'
elseif other_condition:
# trying to access var1 or var2 here will result in a syntax error
This is because the two IF statement bodies are different scopes.
One simple option is to first define them with some default value (e.g. None) outside the function, creating global variables (in the global scope):
var1 = None
var2 = None
def func():
if some_condition:
var1 = 'blah'
var2 = 'asdf'
elif other_condition:
# now var1 and var2 are accessible here,
# but you must check or make sure they've been set
# to the values you want, meaning
# you must ensure func() has been called earlier
# with `some_condition` as true
But often defining global variables is not good practice. One alternative is to have your function accept a state variable that it modifies:
class State(object):
def __init__(self):
self.var1 = None
self.var2 = None
def func(state):
if some_condition:
state.var1 = 'blah'
state.var2 = 'asdf'
elif other_condition:
# can use state.var1 and state.var2
if __name__ == '__main__':
state = State()
# can now call func(state) to read or write state.var1 and state.var2

Discord.py embeded message user reactions

I've been trying to solve this for a couple days with no solution. I want my discord bot to be able to buy digital items, and to buy them I have made a confirmation message and a system where you react to confirm with a 60 seconds timeout with a code I found online.
The problem with that code is it doesnt take into account the message the user reacted, so for example if the user sends two messages and confirms one, they both get executed, also, I can't add another icon like a cancel one. It is pretty important since this is an important function for the bot to work.
Also, making a on_reaction_add function is not viable since I would like my bot to run in various servers and channels at the same time with diferent users sending commands.
#client.event
async def on_message(message):
channel = message.channel
embedVar2 = discord.Embed(title="Item buying", description="<#"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0x9A9B9D)
embedVar2.add_field(name="\u200b", value= "It will cost $" + str(price) + " you will have $" + str(endbal) + " remaining \nReact with ✅ to confirm", inline=False)
await confirm_message.add_reaction("✅") #add a reaction for the user to understand he has to react
def check(reaction, user): #checks if user has reacted
return user == message.author and str(reaction.emoji) == '✅'
try: #waits if it doest get timeout error
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) #calls for function check defined prev
except asyncio.TimeoutError: #if timeout throws error:
embedVar5 = discord.Embed(title="Money transfer", description="<#"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0xFF0A26)
embedVar5.add_field(name="\u200b", value= "It would have cost $" + str(price) + " you would have had $" + str(endbal) + " remaining \nTransaction canceled", inline=False)
await confirm_message.edit(embed = embedVar5) #message edit to canceled
return
else: #if user reacted before timeout
embedVar4 = discord.Embed(title="Money transfer", description="<#"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0x77FF87)
embedVar4.add_field(name="\u200b", value= "It will cost $" + str(price) + " you now have $" + str(endbal) + " remaining \nTransaction confirmed", inline=False)
await confirm_message.edit(embed = embedVar4) #message edit to confirmed
Thanks in advance,
Noel.
To make this message specific, simply add and reaction.message == message in check:
def check(reaction, user): #checks if user has reacted
return user == message.author and str(reaction.emoji) == '✅' and reaction.message == message
If you also want to have a cancel reaction, you should modify check to also allow cancel reactions:
def check(reaction, user): #checks if user has reacted
return user == message.author and str(reaction.emoji) in ['✅','Your cancel reaction here'] and reaction.message == confirm_message
and then check with which reaction the user reacted and do stuff depending on which reaction was used:
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) #calls for function check defined prev
except asyncio.TimeoutError:
embedVar5 = discord.Embed(title="Money transfer", description="<#"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0xFF0A26)
embedVar5.add_field(name="\u200b", value= "It would have cost $" + str(price) + " you would have had $" + str(endbal) + " remaining \nTransaction canceled", inline=False)
await confirm_message.edit(embed = embedVar5)
return
else:
if str(reaction.emoji) == '✅':
embedVar4 = discord.Embed(title="Money transfer", description="<#"+ str(message.author.id) +"> Are you sure you want to buy " + str(conditions[1]) + " quantity of " + str(conditions[0]), color = 0x77FF87)
embedVar4.add_field(name="\u200b", value= "It will cost $" + str(price) + " you now have $" + str(endbal) + " remaining \nTransaction confirmed", inline=False)
await confirm_message.edit(embed = embedVar4)
elif str(reaction.emoji) == 'Your cancel emoji here':
await confirm_message.edit(embed = embedVar5) #execute the same code you executed on TimeoutError
return
References:
Reaction.message

discord.py bot stops responding after I add a new block of code

im new to python and discord.py, this is a repost with updated details and without the block of code that was hard to understand. I have not found an answer to this problem online so it is probably a small mistake on my end.
Problem
I am trying to program a discord.py bot for my server which can do some basic commands.
I wanted to add some functionality into the shell which could allow me to control the bot via python shell.
Before this, I had some basic commands which would work as expected (I do c!help and it responds with an embed message with help)
After I added the code for control via the console, the commands for discord stopped responding as intended.
Desired Behaviour: I type c!boop {user} in discord, The bot send a dm to said user and a logging message is sent in the logging channel. I do c!console in the python shell, my interactive menu comes up
What Happens: I type c!boop {user} in discord, I get nothing back. I do c!console in the python shell, my interactive menu comes up.
As I said, It worked before I added the new code for the Shell.
My Code
The code here has been shortened a lot for the MRE but if you think the full code would be necessary, just ask. Sorry if it still is long, I already removed 3/4 of it to only keep the parts relevant to my problem.
import discord
import time
client = discord.Client()
prefix = 'c!'
#client.event
async def on_message(message):
if message.author == client.user:
return
#This bit is the command for within discord
if message.content.startswith(prefix + "boop"):
#Getting the Victim's user id
victim = str(message.content)
victim = victim.replace(prefix + 'boop ', '')
victim = victim.replace('<#', '')
victim = victim.replace('!', '')
victim = victim.replace('>','')
#Booping the user
user = client.get_user(int(victim))
await message.channel.send("Booped " + user.name)
await user.send('**Boop!**')
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
channel = client.get_channel(int(759798825161326593))
LogMsg = str('`' + current_time + '` ' + message.author.name + ' used command in ' + str(message.channel) + ' `' + message.content + '`')
await channel.send(LogMsg)
#After I added this section, the above command stopped working
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print('USER ID: ' + str(client.user.id))
print('')
print('To Open the Console, type ' + prefix + 'console in the shell')
print('------')
console = str(prefix + 'console')
while 1 == 1:
ConsoleInput = input('')
if ConsoleInput == console:
while 1 == 1:
print('------')
print('Please Select a Module')
print('1 - Announce')
print('99 - Exit Console')
print('------')
ConsoleInput = int(input(''))
if ConsoleInput == 1:
print('------')
print('Module 1 Selected - Announce')
print("What's the id of the channel you want to announce in?")
Channel_id = int(input())
print("Embed? (1 for yes, 2 for no)")
YeNo = int(input())
if YeNo == 1:
print("What is the Title for the Embed message?")
EmbedTitle = str(input())
print("What is the Description for the Embed message?")
announcement = str(input())
print('Announcing')
channel = client.get_channel(Channel_id)
embed=discord.Embed(title=EmbedTitle, description=announcement, color=0xff40ff)
await channel.send(embed=embed)
print("Announced")
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
channel = client.get_channel(int(759798825161326593))
await channel.send('`' + current_time + '` ' + 'Console User used command in Console ' '`' + str(Channel_id) + ' ' + EmbedTitle + ' ' + announcement + ' ' + str(YeNo) + '`')
elif YeNo == 2:
print("What is the announcement?")
announcement = str(input())
print("Announcing")
channel = client.get_channel(Channel_id)
await channel.send(announcement)
print("Announced")
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
channel = client.get_channel(int(759798825161326593))
await channel.send('`' + current_time + '` ' + 'Console User used command in Console ' '`' + str(Channel_id) + ' ' + announcement + ' ' + str(YeNo) + '`')
elif ConsoleInput == 99:
print('------')
print('Exiting Console')
print('You can restart the console by typing ' + prefix + 'console in the shell')
print('------')
break
client.run(TOKEN GOES HERE)
Thanks in advance
Blocking code
It appears that the synchronous code in the on_ready event is what is hanging the bot; waiting for input from the console halts any other code from running, including reacting to commands.
The only way to fix this is to design your announcement command in a different way that doesn't involve using your console, such as having it be a command for your bot.
Sidenote about discord.Client()
Since you're using the lower-level API (discord.Client), you may find it more difficult to develop new commands for your bot. I would recommend using the bot commands framework (discord.ext.commands) that discord.py comes packaged with. The pitch is in the link so instead, here's an example using the framework with your boop command:
import time
import discord
from discord.ext import commands
prefix = 'c!'
TOKEN = ''
client = commands.Bot(command_prefix=prefix)
#client.event
async def on_ready():
print('Logged in as', client.user.name)
#client.command(name='boop')
async def client_boop(ctx, user: discord.User):
"""Boops a user.
Accepted inputs are: ID, mention, name#discrim, or name
Example: c!boop thegamecracks"""
await user.send('**Boop!**')
await ctx.channel.send("Booped " + user.name)
current_time = time.strftime("%H:%M:%S", time.localtime())
log_channel = client.get_channel(759798825161326593)
LogMsg = '`{}` {} used command in {} `{}`'.format(
current_time,
ctx.author.name,
ctx.channel.name,
ctx.message.content
)
await log_channel.send(LogMsg)
client.run(TOKEN)

discord.ext.commands.errors.CommandNotFound: Command ... is not found

My discord bot is able to run its on_message code, but when i try and run a command %ping it errors out and says "discord.ext.commands.errors.CommandNotFound: Command "ping" is not found".
I have imported all the needed modules, wrote client.run(token) at the bottom and defined my token and client object, i didn't deem it necessary to include those lines of code.
I've included await client.process_commands(message) and shifted the code around, i don't know what to do.
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
if online:
await client.change_presence(activity=discord.Game(name="Command prefix: " + compref))
else:
await client.change_presence(status=discord.Status("offline"))
#client.event
async def on_message(message):
#print(message.author)
#print(client.user)
if message.author == client.user:
await client.process_commands(message)
return
else:
#print(message.channel.name)
try:
# Create target Directory
os.mkdir(str(message.author.guild.name))
#print("Guild msg Directory Created ")
except FileExistsError:pass
#print("Guild msg Directory already exists")
try:
os.mkdir(str(message.author.guild.name) + "\\message_logs")
except FileExistsError:pass
#print("Guild msg Directory already exists")
with open(str(message.author.guild.name) + "\\message_logs\\" + str(message.channel.name) + "_message_log.json", "a") as c:
ec = (time.asctime(time.localtime(time.time())) + "; " + str(message.author.name) + ": " + message.content).encode("utf-8")
#print(ec)
c.write(str(ec))
c.write("\n")
c.close()
await client.process_commands(message)
#client.command
async def ping(ctx):
await ctx.send(f"pong {round(client.latency * 1000)}ms")
server = ctx.message.author.guild
server_name = server.name
server_id = server.id
server_owner = server.owner.name
print("")
print("hi")
print("server name: {}\n"
"server id: {}\n"
"server owner: {}"
.format(server_name, server_id, server_owner))
print("")
try:
# Create target Directory
os.mkdir(str(server.name))
print("Guild Directory ", str(server.name), " Created ")
except FileExistsError:pass
#print("Guild Directory ", str(server.name), " already exists")
with open(str(server.name) + "\\" + str(server.name) + "_info.json", "w") as s:
e = "Server name: " + server.name + "\n" + "Server ID: " + str(server_id) + "\n" + "Server Owner: " + server_owner
#print(e)
s.write(e)
s.close()
await client.process_commands(message)
Bot.command is a function that returns a decorator, not a decorator itself. You need to call it:
#client.command()
async def ping(ctx):
await ctx.send(f"pong {round(client.latency * 1000)}ms")
server = ctx.message.author.guild
server_name = server.name
server_id = server.id
server_owner = server.owner.name
print("")
print("hi")
print("server name: {}\n"
"server id: {}\n"
"server owner: {}"
.format(server_name, server_id, server_owner))
print("")
try:
# Create target Directory
os.mkdir(str(server.name))
print("Guild Directory ", str(server.name), " Created ")
except FileExistsError:pass
#print("Guild Directory ", str(server.name), " already exists")
with open(str(server.name) + "\\" + str(server.name) + "_info.json", "w") as s:
e = "Server name: " + server.name + "\n" + "Server ID: " + str(server_id) + "\n" + "Server Owner: " + server_owner
#print(e)
s.write(e)
s.close()
# Remove the process_commands, we're already in a command

Categories

Resources