Mention bot for prefix discord.py rewrite - python

Hey guys im making a discord bot with discord.py rewrite and i have a command when mention the bot it will send you the prefix
But i have this problem
i dont want the bot to send the prefix when there's others text in the message
This is the code:
import discord
from discord.ext import commands
class Support(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee
)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Support(client))

Here are two ideas how it could work :)
import discord
from discord.ext import commands
class Support(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
checkMessage = message.content.split("#")
if checkMessage[0] == "#":
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee
)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Support(client))
import discord
from discord.ext import commands
class Support(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
if self.client.user.mentioned_in(message):
if message.content.startswith("#"):
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee
)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Support(client))

Related

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.

Add reactions to embeds py-cord

Im making a discord bot and i decided to change from prefixed commands to slash command using pycord and my poll command it won't add the reaction it will just send the embed without the reactions
Here is my code:
import discord
import datetime
from discord.ext import commands
class Poll(commands.Cog):
def __init__(self, client):
self.client = client
#discord.slash_command(description = "Create a poll in the current channel")
#commands.has_permissions(manage_channels = True)
#commands.bot_has_permissions(manage_messages = True)
async def poll(self, ctx, *, question):
poll = discord.Embed(
title = "Poll",
description = f"{question}",
timestamp = datetime.datetime.utcnow(),
colour = 0xeeffee)
poll.add_field(name = "Usage:", value = "`✅ Yes | ❎ No`")
message = await ctx.respond(embed = poll)
await message.add_reaction("✅")
await message.add_reaction("❎")
def setup(client):
client.add_cog(Poll(client))
Before i decided to change to slash commands it worked perfectly fine
I don't know what is the problem and i can't find a solutions if it's something simple pls tell because i can't make it work
message = await ctx.respond(embed=poll)
msg = await message.original_response()
await msg.add_reaction("✅")
await msg.add_reaction("❎")
https://docs.pycord.dev/en/stable/api.html#discord.Interaction.original_response

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

discord.py command in cogs file not working

Everything used to work fine when all code was in main.py but then I created cogs folder and created multiple cog files.py and moved code around, now ?servers command is not working. I get
discord.ext.commands.errors.CommandNotFound: Command "servers" is not found
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client = commands.Bot(command_prefix='?', intents=intents, help_command=None)
#client.event
async def on_ready():
print('ARB is logged in.')
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='#ARB'))
client.load_extension("cogs.commands")
client.load_extension("cogs.owner")
client.load_extension("cogs.fun")
client.load_extension("cogs.arb")
cogs/owner.py
import discord
from discord.ext import commands
client = commands.Bot
class Owner(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command
#commands.is_owner()
async def servers(self, ctx):
guildcount = 0
activeservers = client.guilds
print('********************** GUILD LIST **********************')
for guild in activeservers:
guildcount += 1
print(f'{guild.name} - ({guild.id})')
print(f'ARB is in {guildcount} servers.')
def setup(client):
client.add_cog(Owner(client))
You don't have to define client again in the extension, simply delete that line. Also the decorator #commands.command should be called (with ())
import discord
from discord.ext import commands
class Owner(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
#commands.is_owner()
async def servers(self, ctx):
guildcount = 0
activeservers = client.guilds
print('********************** GUILD LIST **********************')
for guild in activeservers:
guildcount += 1
print(f'{guild.name} - ({guild.id})')
print(f'ARB is in {guildcount} servers.')
def setup(client):
client.add_cog(Owner(client))

How to get a list of servers my bot is in discord.py

I want to use a command that prints the list of servers my bot is in. This is what I have. When I use the command it sends "property object at 0x000001988E164270" instead of a list of server names
import discord
from discord.ext import commands
client = discord.Client
activeservers = client.guilds
class OwnerCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("OwnerCommands Is Ready")
#commands.command()
async def servers(self, ctx):
await ctx.send(activeservers)
print(activeservers)
def setup(client):
client.add_cog(OwnerCommands(client))
client.guilds is a list of all guilds that the bot is connected to. You need to iterate over this.
Additionally, activeservers = client.guilds is called before the bot has connected, meaning the list will be empty. Move this to inside your command to have the most up to date list at the time the command is called.
import discord
from discord.ext import commands
client = discord.Client
class OwnerCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("OwnerCommands Is Ready")
#commands.command()
async def servers(self, ctx):
activeservers = client.guilds
for guild in activeservers:
await ctx.send(guild.name)
print(guild.name)
def setup(client):
client.add_cog(OwnerCommands(client))

Categories

Resources