I checked all codes what I can find but they don't work with my bot.What am I doing wrong?
They’re not much different and they all work, but not in my code. No mistakes in the cmd.
my friend can’t do it either. Bot has administrator privileges (I checked)
role = "NEWS"
#bot.event
async def on_member_join(member):
rank = discord.utils.get(member.guild.roles, name=role)
await member.add_roles(rank)
print(f"{member} was given the {rank} role.")
Second
#bot.event
async def on_member_join( member ):
role = discord.utils.get( member.guild.roles, id = 889869064997068810)
await member.add_roles( role )
Third
#bot.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='Unverified')
await member.add_roles(role)
All code without this auto role
import random
import json
import discord
import datetime
from lol import an
from zdar import answer_hello
from zdar import hello_words
from zdar import maternie
from zdar import answer_maternie
from discord.ext import commands
from config0 import settings
bot = commands.Bot(command_prefix= settings['prefix'])
bot.remove_command('help')
#bot.command()
async def clear(ctx, amount = 100):
await ctx.channel.purge( limit = amount )
#bot.command()
async def hello(ctx):
await ctx.send(f',{ctx.message.author.mention}!')
#bot.command()
async def cat(ctx):
await ctx.send(random.choice(an))
#bot.command()
async def time (ctx):
emb = discord.Embed(title = 'Титульник', colour = discord.Color.green(), url = 'https://www.timeserver.ru/cities/by/minsk')
emb.set_author(name = bot.user.name, icon_url = bot.user.avatar_url)
emb.set_footer ( text = ctx.author.name, icon_url= ctx.author.avatar_url)
emb.set_image( url= 'https://i.pinimg.com/originals/3f/82/40/3f8240fa1d16d0de6d4e7510b43b37ba.gif')
emb.set_thumbnail( url= 'https://static.wikia.nocookie.net/anime-characters-fight/images/9/90/Eugo_La_Raviaz_mg_main.png/revision/latest/scale-to-width-down/700?cb=20201114130423&path-prefix=ru')
now_date = datetime.datetime.now()
emb.add_field( name = 'Time', value='Time:{}'.format( now_date))
await ctx.send(embed = emb)
bot.run(settings['token'])
You have to specify the member intent to receive on_member_join events. You can do this while creating your bot object by adding an intent option:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=settings['prefix'], intents=intents)
Note
If your bot is verified you require the SERVER MEMBERS INTENT which you can request on the bot page of your application.
Related
import discord from discord.ext import commands,tasks
client = commands.Bot(
command_prefix='&',
intents=discord.Intents.all(),
description=None,
help_command=commands.MinimalHelpCommand() )
#client.event
async def on_ready():
print('Ready')
await check_status.start()
#tasks.loop(seconds=10)
async def check_status():
user = discord.User
for guild in client.guilds:
for user in guild.members:
for activity in user.activities:
if isinstance(activity, discord.CustomActivity):
print(activity)
Theres only 1 person in my server (me),
My status is "testrfgergerger"
Expected Output:
testrfgergerger
Output:
testrfgergerger
testrfgergerger
(every 10secs)
I am trying to make a bot that once given a command will take away a persons roles and give them back after a certain amount of time. right now im getting the eror unexpected indent.
here is the code:
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
from discord.ext import rolelist, roles, role
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
if re.search("^send.*court$", messageContent):
user_id = message.mentions[0].id
user = message.mentions[0]
await message.channel.send(
f"sending <#{user_id}> to court!"
)
async def listroles(ctx):
user_roles = [role.mention for role in ctx.message.author.roles if role.mentionable]
await message.channel.send(user_roles)
async def roles(ctx):
print(", ".join([str(r.id) for r in ctx.guild.roles]))
role = discord.utils.get(message.guild.roles, name="Jail")
await user.add_roles(role)
async def roles(user.roles):
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role]
roles = ", ".join(rolelist)
print(rolelist)
client = MyClient()
client.run('TOKEN_GOES_HERE')
Python don't use {} like C# or Java, it works with indentation. So your code should be this:
await user.add_roles(role)
async def get_roles(user):
rolelist = [r.mention for r in user.roles if r != ctx.guild.default_role]
roles = ", ".join(rolelist)
print(rolelist)
I have this code which if someone has a role "Server Developer" it is suppose to run the command which is to give someone the role "Jail" for the determent amount n the command but it doesn't work and gives no errors.
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
import asyncio
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#commands.has_role("Server Developer")
#bot.command()
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
You forgot to add #bot.command() on top of your command. Add it between #commands.has_role("Server Developer") and async def court(ctx, user_mentioned: discord.Member, time: int):
Do it like this:
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
import asyncio
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#commands.has_role("Server Developer")
#bot.command()
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = ctx.message.mentions[0].id
user = ctx.message.mentions[0]
role = discord.utils.get(ctx.message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
Using any check decorators like has_role or is_owner, doesn't make the function a command, so you would still have to add #commands.command() or #bot.command():
#bot.command()
#commands.has_role("Server Developer")
async def court(ctx, user_mentioned: discord.Member, time: int):
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
bot.run(TOKNE_GOES_HERE)
you could try adding a check inside the command, something like this:
if not discord.utils.get(ctx.guild.roles, name="Server Developer") in ctx.user.roles:
return
else:
# do something
I want the bot to react to its own message with the ✅ and ❎ emojis for a suggestion command. Here is the code. How do i do it?
import discord
from discord.ext import commands
class suggestions(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(description = 'Add a suggestion for this community!')
async def suggest(self, ctx, *,suggestion):
await ctx.channel.purge(limit = 1)
channel = discord.utils.get(ctx.guild.text_channels, name = '💡│suggestions')
suggestEmbed = discord.Embed(colour = 0xFF0000)
suggestEmbed.set_author(name=f'Suggested by {ctx.message.author}', icon_url = f'{ctx.author.avatar_url}')
suggestEmbed.add_field(name = 'New suggestion!', value = f'{suggestion}')
await channel.send(embed=suggestEmbed)
def setup(bot):
bot.add_cog(suggestions(bot))
Messageable.send returns a discord.Message object, you can then simply .add_reaction
message = await ctx.send(embed=suggestEmbed)
await message.add_reaction('✅')
await message.add_reaction('❌')
Note: You need the unicode of the emoji to react, to get it simply \:{emoji}:
Reference:
Messageable.send
Message.add_reaction
Me, I use this:
#bot.command()
async def suggestion(ctx, *, content: str):
title, description= content.split('/')
embed = discord.Embed(title=title, description=description, color=0x00ff40)
channel = bot.get_channel(insert the channel ID here)
vote = await channel.send(embed=embed)
await vote.add_reaction("✅")
await vote.add_reaction("❌")
await ctx.send("your suggestion has been send")
You can vote using the emojis, enjoy!
I'm trying to make a bot that sends a scheduled message to a specific text channel.
for example at the date of my birthday saying "happy birthday", or also every morning saying "Good morning".
The bot seems to don't work since nothing appears in my text channel.
import discord,random,asyncio,os
from datetime import datetime
from discord.ext import commands
token = '#mytokenhere'
bot=commands.Bot(command_prefix='!')
send_time='01:41' #time is in 24hr format
message_channel_id='0000000000000' #channel ID to send images to
#bot.event
async def on_ready():
print(bot.user.name)
print(bot.user.id)
async def time_check():
await bot.wait_until_ready()
message_channel=bot.get_channel(message_channel_id)
while not bot.is_closed:
now=datetime.strftime(datetime.now(),'%H:%M')
if now.hour() == 1 and now.minute() == 52:
message= 'a'
await message_channel.send(message)
time=90
else:
time=1
await asyncio.sleep(time)
bot.loop.create_task(time_check())
bot.run('token')
Here's how you would do something like this using the tasks extension
from discord.ext import commands, tasks
bot = commands.Bot("!")
target_channel_id = 1234
#tasks.loop(hours=24)
async def called_once_a_day():
message_channel = bot.get_channel(target_channel_id)
print(f"Got channel {message_channel}")
await message_channel.send("Your message")
#called_once_a_day.before_loop
async def before():
await bot.wait_until_ready()
print("Finished waiting")
called_once_a_day.start()
bot.run("token")
You can also do it like this (in case someone stomps on this post):
import discord
import os
import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta
client = discord.Client()
def seconds_until_midnight():
now = datetime.now()
target = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
diff = (target - now).total_seconds()
print(f"{target} - {now} = {diff}")
return diff
#tasks.loop(seconds=1)
async def called_once_a_day_at_midnight():
await asyncio.sleep(seconds_until_midnight())
message_channel = client.get_channel(CHANNEL_ID)
print(f"Got channel {message_channel}")
await message_channel.send("Your message here")
#called_once_a_day_at_midnight.before_loop
async def before():
await client.wait_until_ready()
print("Finished waiting")
client = discord.Client()
called_once_a_day_at_midnight.start()
client.run(os.environ['BOT_TOKEN'])
You can also try to use aiocron.
pip install aiocron
https://github.com/gawel/aiocron
Add below to your bot code before the bot.run(TOKEN)
import aiocron
CHANNEL_ID=1234
#aiocron.crontab('0 * * * *')
async def cornjob1():
channel = bot.get_channel(CHANNEL_ID)
await channel.send('Hour Cron Test')
If you are using discord 2.0 Read the docs.
https://discordpy.readthedocs.io/en/latest/migrating.html#asyncio-event-loop-changes
from discord.ext import commands
import aiocron
TOKEN = 'YOUR TOKEN'
BOT_CHANNELS = 000000000000000000
# you can also import this from else where.
class cronjobs():
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
# print Hello world 20secs.
#aiocron.crontab("* * * * * */20")
async def HelloWorld():
await bot.get_channel(BOT_CHANNELS).send("Hello World!")
class aBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='>', help_command=None)
async def setup_hook(self):
cron = cronjobs(self)
async def close(self):
await super().close()
bot = aBot()
bot.run(TOKEN)