is there a way i can create a invite link using Discord.PY? My code is the following/
import discord
from discord.ext import commands
import pickle
client = commands.Bot("-")
#client.event
async def on_message(message):
message.content.lower()
if message.author == client.user:
return
#checks if the bot it running.
if message.content.startswith("message"):
await message.channel.send("hello there")
#tells the user where they are.
if message.content.startswith("whereami"):
await message.channel.send(f"You are in {message.guild.name} " + \
f"in the {message.channel.mention} channel!")
##Creates Instant Invite
if message.content.startswith("createinvite"):
await create_invite(*, reason=None, **fields)
await message.channel.send("Here is an instant invite to your server: " + link)
client.run('token')
If needed, let me know what other information you need, and if i need to edit this to make it more clear. If I need to import anything else, please inform me as to what libraries are needed.
#client.event
async def on_message(message):
if message.content.lower().startswith("createinvite"):
invite = await message.channel.create_invite()
await message.channel.send(f"Here's your invite: {invite}")
And using command decorators:
#client.command()
async def createinvite(ctx):
invite = await ctx.channel.create_invite()
await ctx.send(f"Here's your invite: {invite}")
References:
TextChannel.create_invite()
discord.Invite - Returned from the coroutine.
Is there a way to create one, but only with one use?
i have an on_message event: if someone type xy, the bot will kick him. and after the kick i want to send him an xy message.(its ready)
and after this i want to send him an invite
Related
I am trying to set up a simple Discord bot for a server, but it only appears to be responding in DMs to commands and not in any server channels. The bot has admin permissions in the server I am trying to get it to respond in.
After doing some looking around I have found no fixes.
Here's the code:
import discord
token_file = open("bot_token.txt", "r+")
TOKEN = str(token_file.readlines()).strip("[]'")
token_file.close()
command_prefix = ">"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("Logged in as: {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(command_prefix):
if message.content == ">help":
await message.channel.send("What do you need help with?")
elif message.content == ">hello":
await message.channel.send("Hi there!")
else:
await message.channel.send("This command is not recognised by our bot, please use the help menu if required.")
else:
return
client.run(TOKEN)
Hope someone can help!
It‘s pretty simple…
For receiving message events in guilds (servers) you need the message intent (discord.Intents.message_content = True), you also have to enable it in the discord developer dashboard.
Discord added a message content intent that has to be used since the first September 2022. if you‘re doing a discord.py tutorial, be aware that it should be a 2.0 tutorial as many things have been updated since then.
Also, think of using the commands extension of discord.py as it is handling some annoying stuff and provides more easier interfaces to handle commands.
I‘ll help you with further questions if there are any
;-)
#kejax has given absolutely the right answer I just want to add how u
can make the use of 'intent' in your code:-
If you want to listen and have access to all available events and data
client = discord.Client(intents=discord.Intents.all())
Full Code :-
import discord
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
You can also specify specific intents by creating a set of the desired discord.Intents constants.
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
Full Code:-
import discord
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('....................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
Soo i want my bot to send a message when someone join but it is not workin
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
and
i want my bot to take a massage from me and send it to the guy i say but this is not workin too
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
and
here is my WHOLE code:
import os, discord,asyncio
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
For making a welcome channel, it is safer to use get_channel instead of get. Because in your code, every time you rename your channel, you need to change your code too, but channel ids cannot be changed until if you delete and create another one with the same name.
Code:
#client.event
async def on_member_join(member):
channel = client.get_channel(YOUR_CHANNEL_ID_GOES_HERE)
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
As for the dm command, I recommend you to get your message as a function parameter. Also you can check when you're DM'ing your bot with the isinstance() function. There is a * before the message parameter though. Its purpose is collecting all of your messages with or without spacing.
Code:
#client.command()
async def dm(ctx, member:discord.Member,*, message):
if isinstance(ctx.channel,discord.DMChannel):
await member.send(f'{ctx.member.mention} has a message for you: \n {message}')
As described in the title, I am new to Python(programming in general) and I tried making a bot, however the bot does not respond to commands. I followed/looked through multiple youtube tutorials & articles, but I cannot find a way to fix my problem.
import discord
from discord.ext.commands import Bot
bot = Bot(".")
#bot.event
async def on_ready():
print("kram is now online")
await bot.change_presence(activity=discord.Game(name="This bot is a WIP"))
#bot.event
async def on_message(message):
if message.author == bot.user:
#bot.command(aliases=["gp"])
async def ghostping(ctx, amount=2):
await ctx.send("#everyone")
await ctx.channel.purge(limit = amount)
#bot.command()
async def help(ctx):
await ctx.send("As of right now, .gp is the only working command.")
bot.run("I'm hiding my token")
Hey why don't you try this instead the same thing but i removed the on message
import discord
from discord.ext.commands import Bot
bot = Bot(".")
#bot.event
async def on_ready():
print("kram is now online")
await bot.change_presence(activity=discord.Game(name="This bot is a WIP"))
#bot.command(aliases=["gp"])
async def ghostping(ctx, amount=2):
await ctx.send("#everyone")
await ctx.channel.purge(limit = amount)
#bot.command()
async def help(ctx):
await ctx.send("As of right now, .gp is the only working command.")
bot.run("I'm hiding my token")
This should work as when using cogs and when you have a command there is no need to put it in the on_message event. i suggest you watch this series(Really helpful while starting out):
https://www.youtube.com/watch?v=yrHbGhem6I4&list=UUR-zOCvDCayyYy1flR5qaAg
I am trying to make a fun bot for just me and my friends. I want to have a command that says what the authors username is, with or without the tag. I tried looking up how to do this, but none worked with the way my code is currently set up.
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
##gets author.
await message.channel.send('You are', username)
client.run('token')
I hope this makes sense, all of the code i have seen is using the ctx or #client.command
The following works on discord.py v1.3.3
message.channel.send isn't like print, it doesn't accept multiple arguments and create a string from it. Use str.format to create one string and send that back to the channel.
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
await message.channel.send('You are {}'.format(message.author.name))
client.run('token')
Or you can just:
import discord
from discord import commands
client = commands.Bot(case_insensitive=True, command_prefix='$')
#client.command()
async def whoAmI(ctx):
await ctx.send(f'You are {ctx.message.author}')
If you want to ping the user:
import discord
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$WhoAmI'):
await message.channel.send('You are', message.author.mention)
client.run('token')
So, I'm working on a discord bot. And am using the on_message() event, which works both on private messages and on servers. I want this to only work in private messages and am unsure of how to go about this.
If anyone can help me, that would be great.
import os
import discord
from discord.ext import commands
TOKEN = ''
quotedUsers = []
client = commands.Bot(command_prefix = '/')
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
await client.change_presence(activity=discord.Game(name='with myself.'))
#client.event
async def on_message(message):
await message.author.send("Recieved: " + message.content)
#client.command()
async def search(ctx, *, question):
await ctx.author.send("Searching: " + question)
client.run(TOKEN)
A message guild also doesn't exist in a group DM, so you have to check if the channel you messaging in is a DM. You can use the dm_channel attribute of a user:
#client.event
async def on_message(message):
if message.channel.id == message.author.dm_channel.id: # dm only
# do stuff here #
elif not message.guild: # group dm only
# do stuff here #
else: # server text channel
# do stuff here #
When a DM is received, it won't have a guild, so you'll be able to use that logic like so:
#client.event
async def on_message(message):
# you'll need this because you're also using cmd decorators
await client.process_commands(message)
if not message.guild:
await message.author.send(f"Received: {message.content}")
References:
Bot.process_commands()
Message.guild - it mentions "if applicable", meaning that it'll return None if it's not in a guild, and rather a DM
f-Strings - Python 3.6+
Hi i had found though playing around that when discord sends a message to the bot as a dm in python this will be done using a discord.channel.DMChanneland if the message is done in the text channel discord.channel.TextChannel.
i have proved this by putting in a type fuct over the object to see what happens in the Message listener.
isinstance(message.channel, DMChannel)