Supposed to send a welcome message when someone joins but nothing happens - python

import discord
import os
intents = discord.Intents.default()
intents.members = True
#client.event
async def on_member_join(member):
if member.guild.name == 'Bot Test Server':
await client.get_channel(927272717227528262).send("https://tenor.com/view/welcome-to-hell-lucifer-morningstar-tom-ellis-lucifer-welcome-gif-18399120")
else:
return
Everything is set correctly and it should send the message, but nothing happens.

Why you didn't initialize client? and I fixed your code since it's not clear nor doesn't look like from dpy docs
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='', intents=discord.Intents.all())
#client.event
async def on_member_join(member):
if member.guild.name == 'Bot Test Server':
channel = client.get_channel(927272717227528262)
await channel.send("https://tenor.com/view/welcome-to-hell-lucifer-morningstar-tom-ellis-lucifer-welcome-gif-18399120")
else:
return
client.run('')

Related

discord.py based bot doesn't work after 2.0 update

So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['ffs','gdsgds']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
client = discord.Client(intents=discord.Intents.default())
client.run('OTkxfsa9WC5G34')
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return 'dont forget uptime robot monitor'
def run():
app.run(host='0.0.0.0',port=8000)
def keep_alive():
t = Thread(target=run)
t.start()
I tried to fix it by my own by changing this line
client = discord.Client(intents=discord.Intents.default())
It has to be some trivial syntax mistake, but I cannot locate it
Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['fdsfds','fsa']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents = intents)
client.run('OTkxMDcxMTUx')
If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents.
intents = discord.Intents.default()
intents.message_content = True
Don't forget to enable it on your bot's developer portal as well.
Also all of that keep alive & flask stuff hints that you're abusing an online host to run a bot on. This brings loads of issues along with it that you can't fix so you should really consider moving away from that. There's posts on a daily basis of people with problems caused by this.
Your code should be:
import discord
from discord.ext import commands # you need to import this to be able to use commands and events
from keep_alive import keep_alive
client = commands.Bot(intents=discord.Intents.default())
#bot.event
async def on_ready(): # you don't need self in here
print('bot is online now', client.user) # you can just use client.user
#bot.event
async def on_message(message): # again, you do not need self
word_list = ['ffs','gdsgds']
if message.author == client.user: # you can use client.user here too
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
keep_alive()
client.run('OTkxfsa9WC5G34') #if this is your real token/you have been using this token since you made the bot, you should definitely generate a new one
To help you, I added some comments to help show you what I have changed and why. As one of the comments in the code says, you should regenerate your bot token at the Discord Developer Portal.
For more info about migrating to 2.0, read the Discord.Py docs

Not able to DM or direct messages in discord.py-self latest version

i am not been able to send dm it gives me an error using module discord.py-self
here is the code
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('BOT IS RUNNING')
async def on_message(self, message):
if message.content.startswith('.hello'):
await message.channel.send('Hello!', mention_author=True)
for member in message.guild.members:
if (member.id != self.user.id):
user = client.get_user(member.id)
await user.send('hllo')
client = MyClient()
client.run('my token')
error
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 0)
In server it is only me and a offilne bot i trying to send a message to bot (as you can see in code)
I would try defining your bot like this:
import discord
from discord.ext import commands
## (Make sure you define your intents)
intents = discord.Intents.default()
# What I always add for example:
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
## Define your bot here
client = commands.Bot(command_prefix= '.', description="Description.", intents=intents)
## Run bot here
client.run(TOKEN)
Then, instead of rendering a client on_message event, I'd instead just set it up like a command which will utilize the prefix as defined for the bot above.
#client.command()
async def hello(ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Better practice: (in my opinion)
Use cogs to keep your code neat. Set up this command in an entirely different file (say within a /commands folder for instance):
/commands/hello.py
import discord
from discord.ext import commands
class HelloCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def hello(self, ctx):
user = ctx.author
await ctx.send(f"Hello, {user.mention}")
dm = await user.create_dm()
await dm.send('hllo')
Then import the cog into your main file:
from commands.hello import HelloCog
client.add_cog(HelloCog(client))
Hope this helps.

discord bot sends infinite messages regardless of user input

I'm trying to make a discord bot respond when someone makes laughing remarks but it infinitely sends gifs whenever someone types anything
code is as follows
import os
import discord
import random
from discord.ext import commands
import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
#bot.event
async def on_ready():
guild_count = 0
for guild in bot.guilds:
print(f"- {guild.id} (name: {guild.name})")
guild_count = guild_count + 1
print("AGOP_Bot is in " + str(guild_count) + " guilds.")
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content == "Lmao" or "Lol" or "lmao" or "lol" and message.author.id != bot_id:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
keep_alive.py
import os
import discord
import random
from discord.ext import commands
# import keep_alive
Bot_Token = os.environ['Bot_Token']
bot = discord.Client()
...
#bot.event
async def on_message(message):
if message.content == "AGOP~hello":
await message.channel.send("https://c.tenor.com/tTXwGpHrqUcAAAAC/summoned.gif")
if message.content in ("Lmao" or "Lol" or "lmao" or "lol") and message.author.id != bot.user:
response_funny = ["https://c.tenor.com/mUAgLfICUC0AAAAC/i-didnt-get-the-joke-abish-mathew.gif","https://c.tenor.com/zdoxFdx2wZQAAAAd/not-funny-joke.gif","https://i.pinimg.com/originals/f5/53/97/f55397a7de1c82b37d6d62e655a0e915.gif","https://jutsume.com/images2/2022/04/16/is-this-some-peasant-joke-meme.png","https://c.tenor.com/FnASqUdvJH4AAAAC/whats-so-funny-john.gif"]
await message.channel.send(random.choice(response_funny))
bot.run(Bot_Token)
# keep_alive.py
In addition to some formatting, I changed some of the variables for the API calls. I commented out the keep_alive.py as I assume you are using that to keep your code hosted on Repl.it or something, and you can just comment it back in. I was also able to get this code to work with my bot and execute as you want.

I want my bot to process commands sent by other bots

This isn't something most people want, but I do.
Code:
#imports
import discord
import os
from keep_alive import keep_alive
from discord.ext.commands import has_permissions, MissingPermissions
from discord.ext import commands
from discord.utils import get
#client name
client = discord.Client()
#log-in msg
#client.event
async def on_ready():
print("Successfully logged in as")
print(client.user)
#prefix and remove default help cmd
client = commands.Bot(command_prefix='H')
client.remove_command("help")
#client.command(pass_context=True)
async def ere(ctx, *, args=None):
await ctx.send("hi")
if discord.utils.get(ctx.message.author.roles, name="MEE6") != None:
if args != None:
await ctx.send("mee6 just spoke!")
else:
await ctx.send("nope")
#client.event
async def on_message(message):
print(message.author)
if "Here" in message.content:
if discord.utils.get(message.author.roles, name="MEE6") != None:
channel = await client.fetch_channel(870023245892575282)
await channel.send("yes")
await client.process_commands(message)
I figured adding "await client.process_commands(message)" to the bottom of on_message would process commands sent by other bots such as MEE6 but no luck. It appears by default on_message can hear bots but commands can not. Any way to get around this?
Any help would be greatly appreciated!
It is a feature of the Bot class to ignore other bot's messages, but #Daniel O'Brien solved it in this thread. The solution is to subclass the bot and override the function which ignores other bots, like this:
class UnfilteredBot(commands.Bot):
"""An overridden version of the Bot class that will listen to other bots."""
async def process_commands(self, message):
"""Override process_commands to listen to bots."""
ctx = await self.get_context(message)
await self.invoke(ctx)
Use ID
for commands:
# from discord.ext import commands as cmds
def is_mee6():
def predicate(ctx: cmds.Context):
return ctx.message.author.id == 159985870458322944:
# 159985870458322944 is ID of MEE6
return cmds.check(predicate)
# Use like it:
# #cmds.command()
# #is_mee6()
# async def ...
for events:
# from discord.ext import commands as cmds
mee6_id = 159985870458322944
# and use it for checks. for Example
#cmds.event
async def on_message(message):
if message.author.id == mee6_id:
# ANY

Not recognizing commands in discord with Python

I run this, it connects however when running it will not return anything when it comes to commands. I've tried changing this to the context return method from on every message. Previously only one message would appear, now none with this method even though both commands are the same with slight differences. What is my error on this? Sorry this is literally my first attempt at a discord bot.
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
discClient = discord.Client()
bot = commands.Bot(command_prefix = "!")
#discClient.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
discClient.run(botToken)
You heading in the right direction commands.Bot have both event and command no need to use a client just for events.
You should either use discord.Client or commands.Bot not both in your case it is commands.Bot.
Also you are running the client only
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
bot.run(botToken)

Categories

Resources