I have previously posted on this same bot and got it working thanks to the people who responded. But, while it finally came to life and turned on, it started spamming messages for no apparent reason. I've looked over the code for typos and can't find any.
Here's the code:
import discord
from discord.ext.commands import bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot (command_prefix = discord)
#client.event
async def on_ready() :
print("Bepis machine fixed")
#client.event
async def on_message(message) :
if message.content == "bepis" :
await client.send_message (message.channel, "bepis")
client.run("Censored Bot Token")
after #client.event is where i need help. also the bottom line if fine this time! turns out i had hit the space bar before the parenthesis and it didn't like that. Help is very appreciated so i can continue adding on to this awesome bot.
It looks like you are sending a message "bepis" in response to the first, then every, message "bepis" - presumably your first response will appear as an entry on the incoming feed which will trigger a second, etc.
Turns out I was not using proper formatting for my bot.
Whenever you say "bepis" in the discord server, the bot will see it and then say "bepis" back, as its intended to do, but, because of my improper formatting, the bot saw itself say "bepis" and responded as if someone else was saying "bepis".
Old lines:
if message.content == "bepis" :
await client.send_message(message.channel, "bepis")
New lines:
if message.content.startswith('bepis'):
await client.send_message(message.channel, "bepis")
So make sure you're using the right format if you're making a bot!
You seemed to already know what the problem is, from this answer you posted. But your solution is far from being able to solve the problem.
on_message is called whenever a new message is sent to anywhere accessible by the bot; therefore, when you type in "bepis" in discord, the bot replies with "bepis", then the message sent by the bot goes into on_message, which the bot re-replies "bepis", and so on...
The simple solution is to check if the message's author is any bot account, or if you want, if the message's author is your bot.
from discord.ext import commands
client = commands.Bot(command_prefix=None)
#client.event
async def on_ready():
print("Bepis machine fixed")
#client.event
async def on_message(message):
# or `if message.author.bot:` # which checks for any bot account
if message.author == client.user:
return
if message.content == "bepis":
await client.send_message(message.channel, "bepis")
client.run("Token")
Note: I also fixed many of your other problems, such as multiple unused imports, another Client, and indentation.
And FYI, command_prefix is only used when command is being processed by a functional command. When you use on_message it has no use, which means you can set it to None.
Related
this is a long one.
so basically im trying to code a Python bot based on Harry Potter, and on my pc im using repl.it
and on my laptop im using PyCharm CE.
my laptop doesnt detect any type of discord (as in import discord) and my pc comes up with the error "AttributeError: 'NoneType' object has no attribute 'strip'". plus repl.it wont allow me to create a .env file and i cant figure out how to use Secrets (Environment Variables). my laptop also will not let me reinstall/uninstall discord and comes up with a LOT of errors (OSErro when i try to force reinstall, permission denied etc. i dont know how to change permissions)
The following is the troublesome code. Note they are the exact same on both platforms
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))'''
Short answer:
In the last line, simply change client.run(os.getenv('TOKEN')) to client.run('<bot-token>') where '<bot-token>' is supposed to be your actual bot token in string format. (In case you aren't sure where to find the bot token of your bot, this link may help)
Long answer:
The client.run() function needs your bot token as the argument in string format. From the error message that you mentioned, it seems that os.getenv('TOKEN') is returning None value, and it seems internally it is trying to strip the given token and failing to strip it because None value doesn't have strip attribute unlike string values. Have you stored your bot token in the key 'TOKEN' of os.environ in string format? Unless you are doing that, I don't think you should use os.getenv('TOKEN') at all. Just enter the bot token as a string, directly as the argument in client.run(). (In case you aren't sure where to find the bot token of your bot, this link may help)
Btw, I am assuming that the ''' in the end is a typo and if not then please remove it!
So, the new code would look like:
import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('<your bot token>')
I've been using the
import os
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle,
activity=discord.Game(''))
print('Successfully logged in as {0.user}'.format(client))
#client.command()
async def hello(ctx):
await ctx.send("Hello! It's great to see you!")
client.run(os.getenv('TOKEN'))
code for commands. I expected to have it respond "Hello! It's great to see you!" when I said !hello (! = prefix). But it returned nothing. Not even an error. Does anyone know why? Also, please don't show discord bot not responding to commands or Discord command bot doesn't responde (python) because I tried both, and neither worked.
I cant chat here because of lack of reputation so I answer it here instead. you should post the full code to make the job easier.
.
Cause 1:
You didn't add a prefix. You need a prefix to use the command
look onto your client. Did you tell the prefix already? like:
client = commands.Bot(command_prefix = "-")
if so, add this and it should work!
.
Cause 2:
You didn't import from discord.ext import commands
this is important if you want to use commands, import that and it should work!
.
Cause 3:
You mixing up client and bot
this might not happen but here it goes, You might mix up client or bot on the decorator, which is #client.command
if you use client (like client = commands.Bot(command_prefix = "-")), use #client.command on the decorator, while if you use Bot (bot = commmands.Bot(command_prefix = "-")) then you should use #bot.command on the decorator.
Hope these will help :D
This is my first time making a discord bot. I've followed every step of the tutorial but my bot doesnt react to the !test command. I do see the bot in the discord server. please help
This is my first time making a discord bot. I've followed every step of the tutorial but my bot doesnt react to the !test command. I do see the bot in the discord server. please help
Firstly, on line 15, your if statement for if(message.content.startswith(!test): is place after the return. The bot will never reach those lines. You will have to move the indent back (indents in python are annoying).
if message.author == client.user:
return
if message.content.startswith('!test'):
await message.channel.send("Hello!")
await client.process_commands(message)
Secondly, await client.process_commands(message) only works with a command client and does not work with the base discord.Client(). The client would have to to be something like
from discord.ext import commands
client = commands.Bot(command_prefix="!")
See What are the differences between Bot and Client? for the difference between discord.Client() and commands.Bot().
I made recently a discord bot for small server with friends. It is designed to answer when mentioned, depending on user asking. But the problem is, when someone mention bot from a phone app, bot is just not responding. What could be the problem?
Code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = '=')
reaction = "🤡"
#bot.event
async def on_ready():
print('Bot is ready.')
#bot.listen()
async def on_message(message):
if str(message.author) in ["USER#ID"]:
await message.add_reaction(emoji=reaction)
#bot.listen()
async def on_message(message):
mention = f'<#!{BOT-DEV-ID}>'
if mention in message.content:
if str(message.author) in ["user1#id"]:
await message.channel.send("Answer1")
else:
await message.channel.send("Answer2")
bot.run("TOKEN")
One thing to keep in mind is that if you have multiple functions with the same name, it will only ever call on the last one. In your case, you have two on_message functions. The use of listeners is right, you just need to tell it what to listen for, and call the function something else. As your code is now, it would never add "🤡" since that function is defined first and overwritten when bot reaches the 2nd on_message function.
The message object contains a lot of information that we can use. Link to docs
message.mentions gives a list of all users that have been mentioned in the message.
#bot.listen("on_message") # Call the function something else, but make it listen to "on_message" events
async def function1(message):
reaction = "🤡"
if str(message.author.id) in ["user_id"]:
await message.add_reaction(emoji=reaction)
#bot.listen("on_message")
async def function2(message):
if bot.user in message.mentions: # Checks if bot is in list of mentioned users
if str(message.author.id) in ["user_id"]: # message.author != message.author.id
await message.channel.send("Answer1")
else:
await message.channel.send("Answer2")
If you don't want the bot to react if multiple users are mentioned, you can add this first:
if len(message.mentions)==1:
A good tip during debugging is to use print() So that you can see in the terminal what your bot is actually working with.
if you print(message.author) you will see username#discriminator, not user_id
Done! Thanks to anyone who helped me out:) Still maybe you have better answers, so, feel free to answer!
I know, this may look like a stupid question, but if you consider that I'm a beginner in making bots for Discord in Python beyond all my other Python knowledge and Stack Overflow being probably a place just for that, I hope it wouldn't. (I'm so new that I literally woke everyone in the home up by my happiness when I saw my bot turned online lol)
As I saw in other posts, tutorial, etc.; (don't mind the usage of , and ; it could be wrong) we have to specify the ID of the channel, so how can we just reply in the channel the user has sent the command in? Maybe getting the ID of the current channel with some type of a command? I don't know.
import discord
TOKEN = 'XXXXX'
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
msg = 'Hi {0.author.mention}'.format(message)
await client.send_message(message.channel, msg)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
(Since I'm lazy regenerating tokens, i made it xxxxx in this example but don't worry i put it in the normal code.)
As I saw, there is no same question even though there are similar ones (i couldnt see an answer or a question definitely because everybody knows how to do that)
The problem is in the send_message part. It gives an error.
You just have to get the channel object and send a message to it using message.channel.send() and not client.send_message()
if message.content.startswith('!hello'):
msg = 'Hi {0.author.mention}'.format(message)
await message.channel.send(msg)
In the future you may wanna try something like this or maybe come across it by any reason:
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command()
#This is defining a '!hello' command
async def hello(ctx):
#In this case you have to use the ctx to send the message
#Good to remember that ctx is NOT a parameter wich the user will give
msg = f'Hi {ctx.author.mention}'
await ctx.send(msg)
There are two ways you can send messages. One is using the on_message but I would recommend against it because it might interfere with other commands in your code.
Example:
import discord
client = discord.Client(command_prefix='!')
#client.event
async def on_ready()
print('Bot is ready')
#example message
#client.command()
async def test(ctx):
await ctx.send('This message is a test')
client.run('YOUR TOKEN')
You can call the test command by doing "!test" in the bot channel.
import os
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='Your Prefered Prefix')
#client.command()
async def hi(ctx):
channel = ctx.message.channel
await channel.send(f"hi {ctx.author.name}!")
client.run(Token)