How to create invite when bot joins server - python

I am trying to create a discord bot and I want it to create an invite to any server it joins. All I need help with is one line of code. I need to actually create the invite but I get:
Atribute Error: 'Guild' object has no attribute 'channel'
It happens on this line:
invite = await guild.channel.create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
The full block:
#client.event
async def on_guild_join(guild):
invite = await guild.channel.create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
with open("invites.json", "r") as f:
invites = json.load(f)
invites[guild.name] = invite # This line might have an issue but i havent got to test it yet
with open("invites.json", "w") as f:
json.dump(invites, f)
I know how to create an invite with a command but theres no ctx on on_guild_join (i dont think). Would i just have to add 'ctx' somewhere in the event arguments?

there is an issue with your code that is explained in the Error you are getting. You are trying to get a channel from a Guild, although they are stored by another name text_channels. You can access this list and select any one, and then create_invite on the particular channel.
Here is how your code should look like:
#client.event
async def on_guild_join(guild):
invite = await guild.text_channels[0].create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
print(invite)
with open("invites.json", "r") as f:
invites = json.load(f)
invites[guild.name] = invite
with open("invites.json", "w") as f:
json.dump(invites, f)

You need to specify channle to create an invite.
For example:
#client.event
async def on_guild_join(guild):
try:
invite = await guild.text_channels[0].create_invite(reason=None, max_age=0, max_uses=0, temporary=False, unique=True)
except IndexError:
pass
This code creates an invite to the first of text channels in guild.

Hey i know its old post but i found an answer for this problem (Its workin for me so..)
Its easy, you can use the code that #Monka posted. But you need to edit this line
invites[guild.name] = invite
to:
invites[str(guild.name)] = invite
New to stackoverflow so sorry for formatting.. Hope you understand it :D

Related

Get member object from mentioned user

I have a discord bot written in python, one of the commands pulls up stats for a user that you ping with >stats #user. I want the bot to repeat the mentioned user's name without pinging them but can't figure out how.
#client.command()
async def stats(ctx,a):
b = str(a)
b = b.replace("<","")
b = b.replace(">","")
b = b.replace("!","")
user = b.replace("#","")
path = 'users/'+user+'.txt'
file = open(path,'r')
lines = file.read()
lines2 = lines.splitlines()
file.close()
await ctx.channel.send('Stats for '+a+'\nExp: '+lines2[0]+'\nMessages Sent: '+lines2[1])
Currently, the bot does say the user's name, but pings them, which results in the user being pinged twice. Once during initiation of the command and once it is carried out. I looked into other questions but couldn't find an answer that worked for me.
I ignored the code where you read from file and focused only on parts you need to change:
#client.command()
async def stats(ctx, a : discord.Member): #here you identify "a" as discord.Member object
await ctx.channel.send(f'Stats for {a.name}') #then you can get name
Check out discord.Member in docs to learn what can you do with it.

Discord bot create unique invite links guild error

I started coding a bot which when prompted would give me a certain number of unique 1 time use invite links to a server in a pre-designated channel inside a server. I am getting error IndexError: list index out of range
the code:
import discord
token = 'my discord bot token'
client = discord.Client()
number_of_links = input('How many links do you want to create? ')
#client.event
async def on_ready():
g = client.guilds[809743502665056306] # getting the error here
c = g.get_channel(809803698212700190)
invites = await discord.abc.GuildChannel.invites(c)
while len(invites) < int(number_of_links):
print('CREATING INVITES')
for i in range(int(number_of_links)): # Create as many links as needed
i = await discord.abc.GuildChannel.create_invite(c, max_uses=1, max_age=0, unique=True) # Create the invite link
break
print('Finished. Exiting soon...')
exit()
client.run(token)
I tried to also use g = client.guilds.get(809743502665056306) but then I get AttributeError: 'list' object has no attribute 'get'.
Am I trying to declare the guild incorrectly?
You can use client.get_guild(809743502665056306) instead of client.guilds[809743502665056306] to solve the error. More details about the get_guild function here.
The on_ready function gets called many times while the bot is running, so you may want to make a command instead of using an event.

Discord.py How can get attachment in message.content

I'm trying to make a bot. It's an archive bot. If some message getting some emoji and some amount, it's moving message to a specific channel that user chooses. I have a problem: it's working well but it's not getting attachment in message.content. Just getting strings, not attachment. How can I fix this problem?
Here is my code:
#Bot.event
async def on_raw_reaction_add(payload):
user = Bot.get_user(payload.user_id)
guild = Bot.get_guild(payload.guild_id)
channel =
guild.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
#some files is opening in these lines...
if #some check points..
else:
await guild.get_channel(to_list[sıra]).send("Written by {} :\n\n {}".format(message.author.mention,message.content))
await guild.get_channel(from_list[sıra]).send("{} your message move to this channel --> {}".format(message.author.mention,Bot.get_channel(to_list[sıra]).mention))
await message.add_reaction("✔️")
How can i get attachment in message.content in on_raw_reaction_add function ?
Try using files in send() method. Example:
await channel.send(
message.content, files=[await f.to_file() for f in message.attachments]
)
In your case it will probably look like that:
await guild.get_channel(to_list[sıra]).send(
"Written by {} :\n\n {}".format(message.author.mention, message.content),
files=[await f.to_file() for f in message.attachments],
)
Reference:
discord.Message.attachments
discord.Attachment.to_file
List Comprehension

discord.py retrieving data from json file not responding

Sorry for the unclear question title. I don't know any other way to put it.
I made a command that says p!channel [channel_id] which basically makes a channel where my bot will respond with "e". I want the command to store the channel_id and guild_id into a json file called channel.json, and when a user sends a message, it will check if the message is in the channel_id channel, and if it is in the channel, will send "e". However, it's not responding and no error codes are showing up. Can someone help? Code is below:
def get_channel(client,message):
with open("channel.json", "r") as f:
e = json.load(f)
return e[str(message.guild.id)]
#client.command()
#commands.has_permissions()
async def channel(ctx, *, channelid):
with open("channel.json", "r") as f:
e = json.load(f)
e[str(ctx.guild.id)] = channelid
with open("channel.json", "w") as f:
json.dump(e,f)
await ctx.send(f"Successfully setup <#{channelid}>")
#client.event
async def on_message(message):
if message.channel.id == get_channel:
await message.channel.send('e')
There are several immediate problems that are keeping this from functioning.
You're only referencing get_channel, not calling it. The channel's ID isn't equal to the function itself, so the message is never sent. You want get_channel(client, message).
Your on_message event ensures that your command never gets called.
You attempt to use ctx.send() instead of ctx.channel.send().
Channel IDs are integers, but command arguments are always read in as strings. Without converting the argument to an integer, comparing it against a channel's ID will always return False.
In addition, there are several things you could improve:
The get_channel function doesn't ever use client, so you could alter your function definition to simply get_channel(message).
Furthermore, channel IDs are globally unique, so you don't need to save the guild ID in order to unambiguously identify a channel.
It would be more efficient not to read the whole file every time you need to check for an ID.
The has_permissions check doesn't check anything if you supply it no arguments, so in your code it does nothing.
You probably don't want your bot to respond to its own messages.
Here's an improved version that reads a saved file on startup, if one exists. It then keeps the IDs as a set in memory, and only opens the file when it needs to add a new ID.
from discord.ext import commands
import json
client = commands.Bot(command_prefix='p!')
try:
with open('channels.json') as f:
client.ids = set(json.load(f))
print("Loaded channels file")
except FileNotFoundError:
client.ids = set()
print("No channels file found")
#client.command()
async def channel(ctx, channel_id):
try:
channel_id = int(channel_id)
except ValueError:
await ctx.channel.send("Channel must be all digits")
return
if channel_id in client.ids:
await ctx.channel.send(f"Channel <#{channel_id}> is already set up.")
return
client.ids.add(channel_id)
with open('channels.json', 'w') as f:
json.dump(list(client.ids), f)
await ctx.channel.send(f"Successfully set up <#{channel_id}>")
#client.event
async def on_message(message):
if message.channel.id in client.ids and message.author != client.user:
await message.channel.send('e')
# Pass processing on to the bot's command(s)
await client.process_commands(message)
client.run(TOKEN)

How to make the command can be disabled on certain servers discord py

I want to make a list with a list of id discord servers that want to disable some of the functions of my bot.
For example: the on_member_join method will not send a message when a person enters the server, and on the other where this function is enabled, it will send that the person has connected to the server. But I don't know how to properly store the id and use it. At the moment there is this:
async def serverid(ctx):
sid = ctx.message.guild.id
await ctx.send(sid)
sid = 705735563696799723 (id server dependent)
that's roughly what I want to get in the end
async def test(ctx):
f = open('/app/commands/servers.txt', 'r')
servers_sid = f.readlines()
now_sid = ctx.message.guild.id
if now_sid == servers_sid: #i know servers_sid = ['id'] or something similar this is what i have a problem with
await ctx.send('Command disabled')
else:
#command execution
i know servers_sid = ['id'] or something similar this is what i have a problem with
You should use splitlines so that you will not carry the \n. I made the check to be not in if it is not in the file then it will just end
async def test(ctx):
with open('/app/commands/servers.txt', 'r') as f:
servers_sid = f.read().splitlines()
now_sid = str(ctx.message.guild.id)
if now_sid not in servers_sid:
await ctx.send('Command disabled')
return
await ctx.send('This is working')
#command execution
I am assuming you txt file is like this.
123
456
789

Categories

Resources