Discord.py auxiliary function not executing text - python

I have a running discord bot using Python, however, I am doing a rewrite to condense the code for other contributors to contribute code by adding an additional function that should reduce the reuse of code.
However, in the code, the function textCom is not able to recognize client.send_message
I have tried adding async to the def of the textCom function, however, this results in no response by the bot.
import discord
TOKEN = 'token'
client = discord.Client()
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
# commands cannot be executed in private messages
if message.channel.type == discord.ChannelType.private:
return
# original code
if message.content.startswith('!text1'):
msg = "text1 executed".format(message)
await client.send_message(message.channel, msg)
# new code I want executed
def textCom(textMessage):
msg = textMessage.format(message)
await client.send_message(message.channel, msg)
if message.content.startswith('!text2'):
textCom("text2 executed")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
The python script run, however, when a user types !text1 the bot replies with "text1 executed" but when a user types !text2 the bot does not reply.

The interpreter should be raising a syntax error when you define on_message, before the bot even starts. You can't have an await inside a non-async function.
Make textCom an async def function and await it when you call it.
#client.event
async def on_message(message):
...
async def textCom(textMessage):
msg = textMessage.format(message)
await client.send_message(message.channel, msg)
if message.content.startswith('!text2'):
await textCom("text2 executed")

Related

Python Bot command not working but event is

Commands not working but events are tried overriding my on_message but that didn't work. When I comment out the second client.event and down client.command works. Any idea of what I could be doing wrong? am I missing something?
import discord
from discord.ext import commands
import random
import time
from datetime import date
client = commands.Bot(command_prefix = '.')
#client = discord.Client()
#client.event
async def on_ready():
print('we have logged in as {0.user}'.format(client))
#client.command()
async def clr(ctx, amount=5):
await ctx.channel.purge(limit=amount)
#client.command(aliases =['should', 'will'])
async def _8ball(ctx):
responses =['As i see it, yes.',
'Ask again later.',
'Better not tell you now.',
"Don't count on it",
'Yes!']
await ctx.send(random.choice(responses))
#client.event()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello how are you?')
Based on the docs (the ones mentioned by moinierer3000 in the comments) as well as other questions on stack (listed below), on_message will stop your commands from working if you do not process the commands.
#client.event()
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello how are you?')
await client.process_commands(message)
Other questions like this:
discord.py #bot.command() not running
Discord.py Commands not working because of a on_message event
Prefixed and non prefix commands are not working together on python discord bot

How do I merge 2 on_message functions in discord.py

I need to merge these 3 on_message functions into 1 function in discord.py rewrite version 1.6.0, what can I do?
import discord
client = discord.Client()
#client.event
async def on_ready():
print('in on_ready')
#client.event
async def on_message(hi):
print("hello")
#client.event
async def on_message(Hey there):
print("General Kenobi")
#client.event
async def on_message(Hello):
print("Hi")
client.run("TOKEN")
The on_message function is defined as:
async def on_message(message)
So you need to check the message contents in the on_message command and do whatever you need to depending on its contents, for that you can use the Message object's content attribute, as defined here here:
#client.event
async def on_message(message):
if message.content == "hi":
print("hello")
elif message.content == "Hey there":
print("General Kenobi")
elif message.content == "Hello":
print("Hi")
Do note though that if you want the bot to actually send a message, you need to replace print(...) with await message.channel.send(...), as that is how you send a message, print only outputs to the terminal by default.

Discord.py - Allow command in specific channel

i need to use my discord command in specific channel , I'm using #client.command()
I mean if i used my command in another channel will be not working
#client.command()
async def w(ctx):
channel = client.get_channel(775491463940669480)
await ctx.send("hello) ```
You can check if ctx.channel is equal to your specific channel.
#client.command()
async def w(ctx):
if ctx.channel.id == 775491463940669480:
await ctx.send("hello)
There is even an easier way to do it without getting the channel. And without having to indent the whole code.
#client.command()
async def w(ctx):
# exit command if not the desired channel.
if ctx.channel.id is not 775491463940669480:
return
#code here
await ctx.send("hello")
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
print("bot is Online")
-
#client.event
async def on_message(message):
cmdChannel = client.get_channel(776179059355942943)
if message.content.lower().startswith('!w'):
if message.channel.id == cmdChannel.id:
#command invoked in command channel - execute it
await client.process_commands(message)
else:
#command attempted in non command channel - redirect user
await message.channel.send('Write this command in {}'.format(cmdChannel.mention))
#client.command()
async def w(ctx, amount):
await ctx.send(f"done {amount}")
async def is_channel(ctx):
return ctx.channel.id = 775491463940669480
#client.command()
#client.check(is_channel)
async def w(ctx):
await ctx.send("hello)
Making the check call the function is_channel makes the code simpler and you can resuse it multiple times.

I'm very new to making discord bots with python and for some reason the bot doesn't respond to commands

As described in the title, I am new to Python(programming in general) and I tried making a bot, however the bot does not respond to commands. I followed/looked through multiple youtube tutorials & articles, but I cannot find a way to fix my problem.
import discord
from discord.ext.commands import Bot
bot = Bot(".")
#bot.event
async def on_ready():
print("kram is now online")
await bot.change_presence(activity=discord.Game(name="This bot is a WIP"))
#bot.event
async def on_message(message):
if message.author == bot.user:
#bot.command(aliases=["gp"])
async def ghostping(ctx, amount=2):
await ctx.send("#everyone")
await ctx.channel.purge(limit = amount)
#bot.command()
async def help(ctx):
await ctx.send("As of right now, .gp is the only working command.")
bot.run("I'm hiding my token")
Hey why don't you try this instead the same thing but i removed the on message
import discord
from discord.ext.commands import Bot
bot = Bot(".")
#bot.event
async def on_ready():
print("kram is now online")
await bot.change_presence(activity=discord.Game(name="This bot is a WIP"))
#bot.command(aliases=["gp"])
async def ghostping(ctx, amount=2):
await ctx.send("#everyone")
await ctx.channel.purge(limit = amount)
#bot.command()
async def help(ctx):
await ctx.send("As of right now, .gp is the only working command.")
bot.run("I'm hiding my token")
This should work as when using cogs and when you have a command there is no need to put it in the on_message event. i suggest you watch this series(Really helpful while starting out):
https://www.youtube.com/watch?v=yrHbGhem6I4&list=UUR-zOCvDCayyYy1flR5qaAg

I have a problem with the message.content in python for a discord bot

When I make a loop the message.content never refreshes.
I tried a lot of things but I don't really know how to code in Python.
import discord
import time
i = 0
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'start':
while True:
print(str(message.content))
client = MyClient()
client.run('TOKEN')
I want to see the message.content refresh when I retype a message in Discord. Can somebody helps me please?
I haven't made a bot as a class, but I've always used # operators before defining functions. My bot looks more like this:
#bot.event # I think this is important
async def on_ready():
await bot.change_presence(game=discord.Game(name="with your mom"))
print(bot.user.name + ' is now up and running')
#bot.command(pass_context=True, description='stuff') # again I think this is important
async def process_command(ctx): # pass context of message into bot
print(dir(ctx)) # show what methods are available (or just look up documentation)
print(ctx)

Categories

Resources