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
Related
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.
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 run the code and send "xd", selfbot replies "lmao", but if another user writes "xd", selfbot does not reply "lmao", What do I do to make it respond to any user or bot?
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
#TOKEN
TOKEN = "u token"
client = discord.Client()
b = Bot(command_prefix = "x")
#b.event
async def on_ready():
print("I ready")
#b.event
async def on_message(message):
if message.content == "xd":
await message.channel.send("lmao")
b.run(TOKEN, bot = False)
you cant do on_message for commands anymore so i recomand you do something like this
#b.command()
async def xd(ctx):
await ctx.send("lmao")
self botting is agaist discord TOS
I'm creating a simple DM part of a bot and I've tried this method but it keeps giving me an error.
Code:
import discord
from discord.ext import commands
TOKEN = "Token Here"
#client.event
async def on_message(message):
if message.author == client.user:
return
me = await client.get_user_info('Snowflake ID Here')
await client.send_message(me, "Message Here")
client.run(TOKEN)
It keeps giving me this error:
NameError: name 'client' is not defined
This method seems like the user needs to send a message but is there a way to do it without the user needing to send a message.
import discord
from discord.ext import commands
client = disord.Client(intents=discord.Intents.all()) # define client
# could also be commands.Bot()
#client.event
async def on_message(message):
if message.author == client.user:
return
me = client.get_user(1234) # user id, must be int type
await me.send("Message Here") # client.send(me, "message here") doesnt work in discord.py version 1.x
client.run("TOKEN")
Client Example
import discord
class MyClient(discord.Client): # defineding client
async def on_ready(self): # event
print('Logged on as', self.user)
async def on_message(self, message): # event
if message.author == self.user:
return
you = self.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
client = MyClient()
client.run('token')
Bot Example
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>') # defineding client
#bot.event
async def on_ready():
print('Logged on as', bot.user)
#bot.event
async def on_message(message):
if message.author == bot.user:
return
you = bot.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
bot.run('token')
I'm making a bot with python and I need help with two things.
Making a welcome message for users that include mentioning the user and mentioning the channel
Making a command that will remove the role "Unverified" and add 4 other roles. I also need it to send a message in the verification channel to make sure the person has been verified and send an embed in general chat telling the user to get self roles.
Well you could try
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix=".")
confirmEmoji = '\U00002705'
#client.event()
async def on_ready():
print("[Status] Ready")
#client.event()
async def on_member_join(ctx, member):
channel = get(ctx.guild.channels,name="Welcome")
await channel.send(f"{member.mention} has joined")
#client.command()
async def ConfirmMessage(ctx):
global confirmEmoji
message = await ctx.send("Confirm")
await message.add_reaction(emoji=confirmEmoji)
def check(reaction, user):
if reaction.emoji == confirmEmoji:
return True
else:
return False
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=check, timeout=10)
roleToRemove = get(ctx.guild.roles,name="unverified")
memberToRemoveRole = get(ctx.guild.members,name=user.display_name)
await memberToRemoveRole.remove_roles(roleToRemove)
Now all you have to do is go to the channel and enter .ConfirmMessage