how to store discord userid using python 3 - discord.py

I'm trying to create a discord bot that could have the option to ban people forever. That means that even if someone unbanned him he will be banned again.
I'm trying to do that with a file that will save the userid but the problem is that the userid is not a string and I can't save it in a file.. but still if I can save it as str and convert it to integer it's not the problem.
My code is:
#client.command()
#commands.has_permissions(administrator=True)
async def testban(bot):
member = client.get_user(int(460688177846550528))
await member.ban(reason='this is a test')
Can someone help me, please?

Discord's User.id is an int. To write it to a file you can simply convert it to a str:
str(userId)
When reading it, you can convert it back to an int:
int(userIdStr)
The User object can then be retrieved using Client.get_user()

Related

Cant get user name discord.py

I am making a bot for my favorite twitch streamer and medium length story short, I need a profile function for the bot. It works when you don't # someone in the second argument, but I want people to be able to see another users profile.
async def profile(ctx, user=None):
if user:
user = discord.User.display_name
else:
user = ctx.message.author.name
with open('users.json', 'r') as f:
file = json.load(f)
await ctx.send(f'PP: ``{file[user]}``')
users.json looks like this:
Your code at its current stage is quite confusing. Let me explain:
You have no method of properly accessing your user, instead calling an empty object.
You're using two separate ways to get the name, via name and display_name, which are two separate names. Adding to this, this method does not take into account that two users may have the same name.
You can define discord.Member within the command itself. If there is no user mentioned, this will default to the command author, ctx.author (which is the same as ctx.message.author).
In the code below, you will notice two ways of I have defined the variable user_info. If you're going to access the numbers based on a discord user's name, I would highly recommend replacing the name with the user id so you can access other discord user information via get_member or similar. Otherwise, feel free to continue using user.name.
Do view the revised code below.
async def profile(ctx, user:discord.Member=None):
if not user:
user = ctx.author
# either continue to save with the name..
user_info = user.name # or user.display_name but don't use both!
# ..or save with their user id
user_info = str(user.id)
with open('users.json', 'r') as f:
file = json.load(f)
await ctx.send(f'PP: ``{file[user_info]}``')

How would i create a private text channel using discord.py?

I want to make it so when a member says: !contact, it opens a private text channel that only the creator can see, as well as the admins. I am very new to discord.py so sorry if this seems like a basic question. Ik there are other questions like this, but none of them seem to work, they say "guild is not defined"
Edit: sorry for not providing code
When posting questions on StackOverflow, you should always try to give examples of what code you have been trying and what you're confused over. Our purpose by answering your questions is to give you a better understanding of a topic and to make sure that you understand what you did wrong, and how to improve.
To get an instance of the current guild that the command is being run in, you can utilize the command context's guild property. Once we have an instance of the guild, we can create a text channel and specify permissions that we want the channel to have. When specifying the channel overwrites, you use a dictionary to map either a role or member to permission overwrite.
import discord
#client.command()
async def contact(ctx):
guild = ctx.guild
admin_role = guild.get_role(0) # Replace with id of admin role
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
admin_role: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True)
}
await guild.create_text_channel("private-channel", overwrites=overwrites) # Replace with name of text channel

How to implement Patreon-only commands for a discord bot?

So i have seen another post with almost the exact same question however, mine is different.
I am fully aware there is a Patreon bot, however to my knowledge this is only valid on servers.
So lets say someone invites my bot, and tries a command that requires them to be a patron. How could my bot written in python do a check to see if they have become a patron for my product? And then set a role for them accordingly. Which i can then do the check on to allow them access to the command or not.
So essentially, it should do what the Patreon bot does, however would work on its own. Examples are such as the Dank Memer bot: which can be invited to any server and if one becomes a patron can use specific commands, otherwise you can't
I've looked around this topic for a while now and haven't been able to find any info on how to check if the user has become a patron or not.
Many thanks in advance!
If you know the patreons. just give them a role [patreons] or any name!
after giving them the role. copy the role id and paste it in patreons_role_id
ok, what this command does is, just it check for the [patreons] role in the member roles! if the [patreons] role is present! it will execute the #your code else it sends a custom message!
#client.event()
async def on_message(message):
if message.content == '!test':
is_patreon = False
for user_roles in message.author.roles:
if user_roles.id == patreons_role_id:
is_patreon = True
break
if is_patreon == True:#your code
else: await message.channel.send('THIS COMMAND IS ONLY AVAILABLE FOR PATREON!')
Let's assume you have a role for your patreons.
#client.command()
#commands.has_roles("PatreonRole")
async def commandname(ctx, args):
#do stuff
There is a way out, but its probably not the right one, so, If you know who your patreons are and you know their discord IDs as well, you can declare an if statement in the command similar to this -
#client.command()
async def your_command_name():
if member.id == #Your 1st Patreon's Discord ID:
#Your Code
elif member.id == #Your 2nd Patreon's Discord ID:
#Your code
else:
await ctx.send("You cannot use that command as you are not a patreon!")
But again this is probably not right way if you have a lot of patreons or you dont know their Discord IDs, but anyways this way was the only way I could come up with.
I hope that helped. :)

Bot wont properly print member_count

So I'm new to Python and I decided to take the plunge and make a Discord bot for personal use in my server. I like the idea of having full control over what features my bot will have so I'm slowly building the bot. Currently I want my bot to show the current number of members in the server when called with a command
import discord
from discord.ext import commands
#botbot.command()
async def server(ctx):
guild = discord.Guild.member_count
await ctx.send(guild)
I know I'm most likely way off with my code here.
While the bot is sending a message into the chat, its formatted as:
<property object at 0x046036C0>
While I would like to have it say something like "This server has {some number} members."
Any advice is really appreciated!
Thank you for your time.
Edit: botbot is the name for my bot, just so thats clear.
discord.Guild is the class. You want to get the guild the command is in from the invocation context:
#botbot.command()
async def server(ctx):
await ctx.send(f"This server has {ctx.guild.member_count} members.")
The method member_count is not really what you want in this occasion, the guild object has a list called members, so it's as easy as getting the length of that list like so:
#botbot.command()
async def server(ctx):
guild = len(discord.guild.members)
await ctx.send(guild)
EDIT: And indeed you have a typo with using "Guild" instead of "guild"

'NoneType' object has no attribute 'send' - Discord Bot

What I'm trying to do is to make my discord bot send a message to a channel in my server when I supply it the command "!say" through DM.
I've tried a lot of different codes, but usually, it ends up with the Attribute Error "X object has no attribute Y"
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command()
async def say(ctx):
channel = bot.get_channel('584307345065246725')
await channel.send(ctx)
The error message always shows up when I DM the bot, expecting for it to send the required message.
There is a pretty simple thing going on with your code snippet that needs to be corrected before it'll do what you're attempting to make it do.
First off, take a look at the API section for Client.get_channel (which you're calling):
get_channel(id)
Returns a channel with the given ID.
Parameters
id (int) – The ID to search for.
Returns
The returned channel or None if not found.
Return type
Optional[Union[abc.GuildChannel, abc.PrivateChannel]]
So, when you do this: channel = bot.get_channel('584307345065246725'), you're passing an incorrect argument. As per the API, the only parameter must be an int, but you are passing a string. Simply get rid of the single quotes and that should be fine.
Protip: Under "Returns," the API states that it can return None if the channel isn't found, which is what is happening to you, since you're passing in a string. Hence, channel becomes the NoneType object you see in the error. So when you do channel.send... you get the picture.
The channel id is an int, not a string
#bot.command()
async def say(ctx):
channel = bot.get_channel(584307345065246725)
await channel.send(ctx)
What I didn't quite understand is why you couldn't just do:
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def say(ctx):
await ctx.send(ctx)
But I could be mistaken about what you are trying to do.

Resources