My discord.py bot does not read any messages - python

I was making another discord.py bot in replit (yes, i know replit isn't optimal, but it's a small bot, and replit can easily do everything i need from it), and followed the exact steps I used when making another bot of mine that works flawlessly. Then, i tested it, and nothing happened. I checked the code, nothing there, then the developer options, everything was fine, and the bot permissions. The bot was on administrator. On top of this, the bot kept showing up as offline in discord, even though the project was running just fine. The token is okay, and I even asked chat GPT multiple times, and nothing worked.
This is my code:
import discord
import os
from keep_alive import keep_alive
from datetime import datetime
import requests, random
time = datetime.now().strftime('%H:%M:%S')
timeSplit = time.split(":")
hoursFiltered = int(timeSplit[0]) - 8
minutesFiltered = int(timeSplit[1])
cstHoursFiltered = hoursFiltered + 2
estHoursFiltered = hoursFiltered + 3
cstHours = int(timeSplit[0]) - 2
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
wyvernID = 688807968120373319
reminding = 0
help = "LIST OF COMMANDS:\n%kat: gives you a random image of a cat\n%opendms: opens dms with the bot (it sends you a message)\n%kathelp: seriously?\n%pick: type this command followed with either 2 or 3 options seperated by spaces, and it will chose one. (ex: %pick kat cat) Make sure you do NOT end your message with a space.\n"
#client.event
async def on_ready():
print ('We have logged in as {0.user}'.format(client))
while True:
if int(cstHours) == 15 and int(minutesFiltered) == 30 and reminding == 1:
for i in range(3):
await client.get_user(wyvernID).send("Wake up pls :)")
#client.event
#client.event
async def on_message(message):
global reminding
if message.author == client.user:
return
if str(message.author) in ["Cheez#5224"]:
await message.channel.send("?")
if message.content.startswith("%kat"):
response = requests.get("https://api.thecatapi.com/v1/images/search")
cat = response.json()
catDict = dict(cat[0])
await message.channel.send(str(catDict['url']))
if message.content.startswith("%opendms"):
await message.author.send("Dms Are Open With Me")
if message.content.startswith("%kathelp"):
print(help)
await message.channel.send(help)
if message.content.startswith("%pick"):
pickrawlist = message.content.split(" ")
if len(pickrawlist) >= 3:
choice = random.randint(1, len(pickrawlist) - 1)
await message.channel.send(pickrawlist[choice])
else:
await message.channel.send("An Error Has Occured. Please make sure you have no less than 2 choices.")
if "kat" in message.content.lower():
await message.add_reaction("<:👍>")
try:
keep_alive()
client.run(os.getenv('TOKEN'))
except discord.errors.HTTPException:
print("\n\n\nBLOCKED BY RATE LIMITS\nRESTARTING NOW\n\n\n")
os.system("python restarter.py")
os.system('kill 1')
"keep_alive" and "restarter" work just fine, as I used the same code that worked in my other bot. To be clear, the project hosting is fine, but the bot appears offline in discord. I gave the bot every permission in discord developers, and there is NO ERROR. I know that the reading is the issue, becuase I made the project print a message when a message is sent, and nothing is printed. I honestly have no idea what's happening, and would like help. If anyone can help me, that would be much appreciated :)

Related

Nextcord (discord.py fork) - How can I return to Discord that a command is currently running?

I have a Discord bot with a command that take some time to be completed (about 5 seconds).
When the command take too much time to complete without any responses to Discord servers, I've seen that Discord make the command crash, and delete the Context, so when I send a response, it raises an error to say that the Context does not exists.
MEE6 by example, when executing a command, Discord returns:
Sending command...
And when MEE6 receive the command, it says:
MEE6 is thinking...
But my bot does not.
How can I do like MEE6, return to Discord that my command is still running ?
Im using Nextcord (a discord.py fork) so discord.py anwsers will works too.
Minimal reproductible code:
import requests, nextcord
from nextcord.ext import commands
bot = commands.Bot(intents=nextcord.Intents.all()) # be sure to enable every discord intents in the discord dev portal
#bot.slash_command(name='axolotl')
async def axolotl(ctx): # do things that take a lot of time
r = requests.get('https://axolotlapi-test.kirondevcoder.repl.co/reddit?nsfw=0', timeout=2)
if r.status_code == 200:
data = r.json()['data'][0]
embed = nextcord.Embed(title='Axolotl !', description=data['text'] or 'No text content.')
medias = ""
for media in data['media']:
embed.set_image(media)
await ctx.send('', embed=embed)
else:
await ctx.send('', embed=nextcord.Embed(title='Axolotl !', description='There was an error while contacting the API.'))
bot.run('your token here')
I know that the ctx object is not a nextcord.Context object but a nextcord.interaction.Interaction object and I think the API docs of this class can be found at https://docs.nextcord.dev/en/stable/api.html#nextcord.Interaction but im not sure.
I allready tried to make the bot typing on the channel, but it does not change anything:
#bot.slash_command(name='axolotl')
async def axolotl(ctx):
async with ctx.channel.typing():
r = requests.get('https://axolotlapi-test.kirondevcoder.repl.co/reddit?nsfw=0', timeout=2)
if r.status_code == 200:
data = r.json()['data'][0]
embed = nextcord.Embed(title='Axolotl !', description=data['text'] or 'No text content.')
medias = ""
for media in data['media']:
embed.set_image(media)
await ctx.send('', embed=embed)
else:
await ctx.send('', embed=nextcord.Embed(title='Axolotl !', description='There was an error while contacting the API.'))
(I only provided the command code, else its the same code as the minimal reproductible code)
Can someone help please ?
If your commands take a while to execute then you can defer() to tell discord that your commands are going to take a while (and get the "Bot is thinking..." message).
So add await ctx.response.defer() at the start of your command. You can then use the followup attribute to send a message and "respond" to the slash command.
#bot.slash_command(name='axolotl')
async def axolotl(ctx):
await ctx.response.defer()
async with ctx.channel.typing():
r = requests.get('https://axolotlapi-test.kirondevcoder.repl.co/reddit?nsfw=0', timeout=2)
if r.status_code == 200:
data = r.json()['data'][0]
embed = nextcord.Embed(title='Axolotl !', description=data['text'] or 'No text content.')
medias = ""
for media in data['media']:
embed.set_image(media)
await ctx.followup.send('', embed=embed)
else:
await ctx.followup.send('', embed=nextcord.Embed(title='Axolotl !', description='There was an error while contacting the API.'))

Ignoring Exception in_onmessage

I am new to making Discord Bots using Discord API and python, and apparently my code is acting a bit strange since i added Databases, i have used replit for the coding.
My code is:
import discord
import os
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get("http://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return quote
#client.event
async def on_ready():
print('{0.user}'.format(client) + ' has successfully logged in.')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.ltt help'):
await message.channel.send('hello')
if input.content.startswith('.ltt inspire'):
quote = get_quote()
await message.channel.send(quote)
client.run(os.getenv('TOKEN'))
And when i try to execute it, it gives me the following error after sucessfully executing:
The error causes the bot to be unresponsive, even after mutliple triez of executing .ltt inspire and .ltt help, it seems their is a bug, or error. Even after rechecking the code the error persists.
Note: The following code is from a tutorial, if you want to refer to that here is the link: https://www.youtube.com/watch?v=SPTfmiYiuok
Note: I had not merged .ltt inspire and .ltt help before. When I did .ltt inspire was the only code that worked. .ltt help is not responding.
if message.content.startswith('.ltt inspire'):
quote = get_quote()
await message.channel.send(quote)
just make sure whenever you start a new line in on_message() you always stat that it is a message and not an input

Discord bot isn't responding to commands

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

Why is my discord bot spamming?

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.

DM commands to discord bot

I recently had the idea of DMing my bot commands. For example, a command which would unban me from every server that the bot is on.
Unfortunately I don't have any starting point for the command because I'm not even sure DMing commands is possible.
Keywords like discord.py, command or DM are so common in google that finding any good info on the topic is very hard.
I'm looking for a way for the bot to receive DMs as commands and only accept them from me (my ID is stored in the variable ownerID if anyone wants to share any code).
While I'm mostly looking for the above, some code for the DM unban command would also be very helpful.
EDIT: I was asked to show some example code from my bot. Here is the code for the command number which generates a random number and sends it in a message. I hope this gives you an idea of how my bot is made:
#BSL.command(pass_context = True)
async def number(ctx, minInt, maxInt):
if ctx.message.author.server_permissions.send_messages or ctx.message.author.id == ownerID:
maxInt = int(maxInt)
minInt = int(minInt)
randomInt = random.randint(minInt, maxInt)
randomInt = str(randomInt)
await BSL.send_message(ctx.message.channel, 'Your random number is: ' + randomInt)
else:
await BSL.send_message(ctx.message.channel, 'Sorry, you do not have the permissions to do that #{}!'.format(ctx.message.author))
You can send commands in private messages. Something like
#BSL.command(pass_context=True)
async def unban(ctx):
if ctx.message.channel.is_private and ctx.message.author.id == ownerID:
owner = await BSL.get_user_info(ownerID)
await BSL.say('Ok {}, unbanning you.'.format(owner.name))
for server in BSL.servers:
try:
await BSL.unban(server, owner) # I think having the same name should be fine. If you see weird errors this may be why.
await BSL.say('Unbanned from {}'.format(server.name))
except discord.HTTPException as e:
await BSL.say('Unbanning failed in {} because\n{}'.format(server.name, e.text))
except discord.Forbidden:
await BSL.say('Forbidden to unban in {}'.format(server.name))
else:
if ctx.message.author.id != ownerID:
await BSL.say('You are not my owner')
if not ctx.message.channel.is_private:
await BSL.say('This is a public channel')
should work. I'm not sure what happens if you try to unban a user who is not banned, that may be what raises HTTPException

Categories