I want my bot to process commands sent by other bots - python

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

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.

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

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('')

How do I use discord commands

I have tried making a bot in discord.py and i cant figure out how to use discord.ext.
The part that doesn't work is this:
bot = commands.Bot(command_prefix='.')
#bot.command()
async def test(ctx, arg):
await ctx.channel.send(arg)
When I type .test whatever in discord nothing happens
Is it because of the api update?
If so what do I need to change
This is the entire code:
import os
import discord
import asyncio
from dotenv import load_dotenv
from discord.ext import commands
from discord.ext import bot
bot = commands.Bot(command_prefix='$')
#bot.command()
async def test(ctx, arg):
await ctx.channel.send(arg)
load_dotenv()
token = os.getenv("TOKEN")
client = discord.Client()
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
f = open("muteMsg.txt", "r")
muteMsg = f.read()
f.close()
print('Message from {0.author}: {0.content}'.format(message))
id = message.author.id
if id == 0:
await message.delete()
if muteMsg == "1":
await message.channel.send(f"stfu {message.author.mention}")
elif message.content.startswith('good bot') or message.content.startswith('Good bot'):
await message.channel.send(':)')
elif message.content.startswith('bad bot') or message.content.startswith('Bad bot'):
await message.channel.send(':(')
elif message.content.startswith('.rickroll'):
await message.channel.send('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
elif message.content.startswith('.help'):
await message.channel.send('commands list:\n.help: shows this\n.rickroll: well youll have to try yourself\n')
elif message.content.startswith('.togglemutemsgs'):
if muteMsg == "0":
f = open("muteMsg.txt", "w")
f.write("1")
f.close()
await message.channel.send('mute messages on')
elif muteMsg == "1":
f = open("muteMsg.txt", "w")
f.write("0")
f.close()
await message.channel.send('mute messages off')
client = MyClient()
client.run(token)
The core issue here is that while you do instantiate discord.ext.commands.Bot on line 9 you never actually use it, instead calling .run() on your subclass of discord.Client which does not interact with your defined method in any way.
The simplest way of getting your command to work is to change your last line from client.run(token) to
bot.run(token)
but your handlers of on_ready and on_message events will not work anymore - you should learn more to figure out why and how to solve it.
As a side note: you really shouldn't be putting any complex logic in on_message handler and you definitely should not be opening files there.
Well, If you want to take input from user ,you need to use async def test(ctx, *, arg), Try using the code below:
#bot.command()
async def test(ctx, *,arg):
await ctx.channel.send(arg)
And also beware of the command_prefix properly. Thank you :)
To use commands extension, you need to define a bot via commands.Bot because discord.Client doesn't have any infrastructure to make commands.
So you should change your inheritance in class MyClient, it should directly inherit from the commands.Bot. And you should pass the args/kwargs to your MyClient class, then you should run that classes instance rather than discord.Client.

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)

Delete Messages with Python Discord bot?

I'm trying to make a Python Discord Bot that firstly can delete messages within a channel. I wanted it to be Terminator 3 themed so it would start out by the user saying Skynet then the bot asks to activate Y or N? and when the user types Y it would delete all the messages in the channel if the user typed N it would say judgment day is inevitable. any help would be greatly appreciated.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
token = 'Token'
Client = discord.Client()
client = commands.Bot(command_prefix = '!')
#client.event
async def on_ready():
print("Skynet Online")
#client.event
async def on_message(message):
if message.content == 'skynet':
await client.send_message(message.channel, 'Execute Y/N?')
#asyncio.coroutine
async def delete_messages(messages):
if message.content == 'Y':
await client.delete_messages()
client.run('Token')
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
#has_permissions(manage_messages=True, read_message_history=True)
#bot_has_permissions(manage_messages=True, read_message_history=True)
async def purge(ctx, limit: int = 100, user: d.Member = None, *, matches: str = None):
"""Purge all messages, optionally from ``user``
or contains ``matches``."""
logger.info('purge', extra={'ctx': ctx})
def check_msg(msg):
if msg.id == ctx.message.id:
return True
if user is not None:
if msg.author.id != user.id:
return False
if matches is not None:
if matches not in msg.content:
return False
return True
deleted = await ctx.channel.purge(limit=limit, check=check_msg)
msg = await ctx.send(i18n(ctx, 'purge', len(deleted)))
await a.sleep(2)
await msg.delete()
That is the command to delete messages

Categories

Resources