import discord
import asyncio
import aiohttp
client = discord.Client()
# Open the tokens.txt file and read the tokens into a list
try:
with open("tokens.txt", "r") as f:
tokens = f.read().split("\n")
except FileNotFoundError:
print("tokens.txt not found. Please create the file and add your tokens.")
exit()
# Keep track of the current token index
token_index = 0
# Webhook URL
webhook_url = "https://discord.com/api/webhooks/ENTERURWEBHOOK"
#client.event
async def on_ready():
# Read the file containing the Discord IDs
try:
with open("newusers.txt", "r") as f:
newusers = f.read().split("\n")
except FileNotFoundError:
print("newusers.txt not found. Please create the file and add the Discord IDs.")
exit()
try:
with open("defaultpfp.txt", "r") as f:
defaultpfp = f.read().split("\n")
except FileNotFoundError:
print("defaultpfp.txt not found. Please create the file and add the Discord IDs.")
exit()
try:
with open("both.txt", "r") as f:
both = f.read().split("\n")
except FileNotFoundError:
print("both.txt not found. Please create the file and add the Discord IDS.")
# Iterate through the IDs
for id in newusers:
if not id.strip():
continue
# Get the member from the Discord API
try:
member = await client.fetch_user(int(id))
except ValueError:
print(f"Invalid ID: {id}. Skipping...")
continue
while True:
try:
#Use the current token
await client.start(tokens[token_index])
#check if the member dms are open
if member.dm_channel is not None:
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(webhook_url,adapter=discord.AsyncWebhookAdapter(session))
await webhook.send(f":date: {member.name}#{member.discriminator} ({member.id})")
break
except discord.errors.HTTPException as e:
if e.status == 429:
token_index = (token_index+1) % len(tokens)
await asyncio.sleep(e.response.headers["Retry-After"])
else:
raise e
for id in defaultpfp:
if not id.strip():
continue
try:
member = await client.fetch_user(int(id))
except ValueError:
print(f"Invalid ID: {id}. Skipping...")
continue
while True:
try:
await client.start(tokens[token_index])
if member.dm_channel is not None:
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(webhook_url, adapter=discord.AsyncWebhookAdapter(session))
await webhook.send(f":new: {member.name}#{member.discriminator} ({member.id})")
break
except discord.errors.HTTPException as e:
if e.status == 429:
token_index = (token_index+1)% len (tokens)
await asyncio.sleep(e.response.headers["Retry-After"])
else:
raise e
for id in both.txt:
if not id.strip():
continue
try:
member = await client.fetch_user(int(id))
except ValueError:
print(f"Invalid ID: {id}. Skipping...")
continue
while True:
try:
await client.start(tokens[token_index])
if member.dm_channel is not None:
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(webhook_url, adapter=discord.AsyncWebhookAdapter(session))
await webhook.send(f":date: + :new: {member.name}#{member.discriminator} ({member.id})")
break
except discord.errors.HTTPException as e:
if e.status == 429:
token_index = (token_index+1)%len (tokens)
await asyncio.sleep(e.response.headers["Retry-After"])
else:
raise e
I am making a Discord Self-Bot (I know they are against Discord TOS) that checks through 3 files containing Discord IDs (1 Line is 1 ID on every one of them)
newusers.txt
defaultpfp.txt
both.txt
Now then I also have tokens.txt (1 Line is 1 Token).
I use 1 token a time from 'tokens.txt' to check if the users from the 3 text files have their Discord DMs open. If a user from newusers.txt have their DMs open then I would like the script to send me that users information (username&tag ID) and an special emoji so I know it's coming from newusers.py, the :date: emoji from Discord to my webhook. The same way as before, I want for every user from defaultpfp.txt who has their DMs open for his information to be sent to me in my webhook with the :new: emoji this time. Lastly for both.txt for people with dms open from there , I want to be sent their information with ':new: and :date:' emojis. Also I have a added a feature where, every time the token seems to get rate limited the script will go on with the next token from tokens.txt.
The error am getting here is tokens.txt not found. Please create the file and add your tokens.
I am honestly not sure what is wrong, the tokens.txt file does exist in path and tokens are also added in it (Tokens are also in the guild server the other users from the 3 text files are). Any help is appreciated, I pray that someone can help me out as I have been struggling for quite some time with this.
Related
Am using discord.py library to create a Discord self-bot that reads through a .txt file I already have filled with Discord IDs and checks their role in a guild server, if the role matches the role am looking for then their ID is saved in a new notepad called 'roletrue.txt'. I have been stuck for quite some time now, any help is appreciated! I know it is against Terms of Services however I still do it.
Code:
import discord
client = discord.Client()
#client.event
async def on_ready():
# Read the file containing the Discord IDs
with open("ids.txt", "r") as f:
ids = f.read().split("\n")
# Get the guild and the role
guild = client.get_guild('GUILD_ID')
role = discord.utils.get(guild.roles, name="ROLE_NAME")
# Iterate through the IDs
for id in ids:
# Get the member from the guild
member = await guild.fetch_member(int(id))
if role in member.roles:
with open("roletrue.txt", "a") as f:
f.write(f"{id}\n")
print(f"Discord ID {id} has the role {role.name}.")
else:
print(f"Discord ID {id} does not have the role {role.name}.")
client.run("TOKEN", bot = False)
Error:
File "C:\Users\spath\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\spath\OneDrive\Υπολογιστής\NFT Vict Scrape\checkroles.py", line 13, in on_ready
role = discord.utils.get(guild.roles, name="Customer")
^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'roles'
I tried rewriting the code from scratch and check discord library and searched online and couldn't find a answer for my problem.
Change
guild = client.get_guild("GUILD_ID")
to
guild = await client.fetch_guild("GUILD_ID")
Get only returns the guild object if it's cached - if it's returning None then it's not so use fetch instead.
You will have to use await in order to fetch guild id and the roles from it,
try using this:
guild = await client.fetch_guild("GUILD_ID")
or if it doesn't work, try using discord utils.
I have discord bot and it checks whether streamer is live or not. And I have a function that prevents it from spamming when someone is live:
if status is True:
async for message in channel.history(limit=2000):
if message.content == f"`Hey #everyone, {twitch_name} is live! Check it out:" + f"https://www.twitch.tv/{twitch_name}`":
break
else:
async for member in guild.fetch_members(limit=None):
if member.id == int(user_id):
await member.add_roles(role)
await channel.send(f"`Hey #everyone, {twitch_name} is live! Check it out:" + f"https://www.twitch.tv/{twitch_name}`")
print(f"{user} started streaming. Sending a notification.")
break
And I wonder if there is the way to do same with embeds, but idk what to use. I though I can use if embed = twitch_embed: break instead of if message.content.
I want to send both message and embed when someone is live one time per stream each like mee6 does:
And I want to combine message and embed antispam function in the code. Please help! All my code here if you need:
import os
import json
import discord
import requests
from discord.ext import tasks, commands
from server import ping
from twitchAPI.twitch import Twitch
from discord.utils import get
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
# Authentication with Twitch API.
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
twitch = Twitch(client_id, client_secret)
twitch.authenticate_app([])
TWITCH_STREAM_API_ENDPOINT_V5 = "https://api.twitch.tv/kraken/streams/{}"
API_HEADERS = {
'Client-ID': client_id,
'Accept': 'application/vnd.twitchtv.v5+json',
}
user_info = twitch.get_users(logins=['turb4ik'])
user_id = user_info['data'][0]['id']
print(user_info)
# Returns true if online, false if not.
def checkuser(user):
try:
userid = twitch.get_users(logins=[user])['data'][0]['id']
url = TWITCH_STREAM_API_ENDPOINT_V5.format(userid)
try:
req = requests.Session().get(url, headers=API_HEADERS)
jsondata = req.json()
if 'stream' in jsondata:
if jsondata['stream'] is not None:
return True
else:
return False
except Exception as e:
print("Error checking user: ", e)
return False
except IndexError:
return False
# Executes when bot is started
#bot.event
async def on_ready():
# Defines a loop that will run every 10 seconds (checks for live users every 10 seconds).
#tasks.loop(seconds=10)
async def live_notifs_loop():
# Opens and reads the json file
with open('streamers.json', 'r') as file:
streamers = json.loads(file.read())
# Makes sure the json isn't empty before continuing.
if streamers is not None:
# Gets the guild, 'twitch streams' channel, and streaming role.
guild = bot.get_guild(690995360411156531)
channel = bot.get_channel(785523710362124298)
role = get(guild.roles, id=835581408272580649)
# Loops through the json and gets the key,value which in this case is the user_id and twitch_name of
# every item in the json.
for user_id, twitch_name in streamers.items():
print("checking" + " " + str(twitch_name))
# Takes the given twitch_name and checks it using the checkuser function to see if they're live.
# Returns either true or false.
status = checkuser(twitch_name)
# Gets the user using the collected user_id in the json
user = bot.get_user(int(user_id))
# Makes sure they're live
if status is True:
# Checks to see if the live message has already been sent.
#limit = 0
#limit += 1
async for message in channel.history(limit=2000):
# If it has, break the loop (do nothing).
if message.content == f"`Hey #everyone, {twitch_name} is live! Check it out:" + f"https://www.twitch.tv/{twitch_name}`":
break
# If it hasn't, assign them the streaming role and send the message.
else:
# Gets all the members in your guild.
async for member in guild.fetch_members(limit=None):
# If one of the id's of the members in your guild matches the one from the json and
# they're live, give them the streaming role.
if member.id == int(user_id):
await member.add_roles(role)
# Sends the live notification to the 'twitch streams' channel then breaks the loop.
'''twitch_embed = discord.Embed(
title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch!",
color=0xac1efb
)'''
#twitch_embed.add_field(name='**Game**', value='add value',inline=True)
#twitch_embed.add_field(name='**Viewers**', value='add value',inline=True)
#twitch_embed.set_image(url=f'\nhttps://www.twitch.tv/{twitch_name}')
await channel.send(f"`Hey #everyone, {twitch_name} is live! Check it out:" + f"https://www.twitch.tv/{twitch_name}`")
#await channel.send(embed=twitch_embed)
print(f"{user} started streaming. Sending a notification.")
break
# If they aren't live do this:
else:
# Gets all the members in your guild.
async for member in guild.fetch_members(limit=None):
# If one of the id's of the members in your guild matches the one from the json and they're not
# live, remove the streaming role.
if member.id == int(user_id):
await member.remove_roles(role)
# Checks to see if the live notification was sent.
async for message in channel.history(limit=200):
# If it was, delete it.
if str(user.mention) in message.content and "is now streaming" in message.content:
await message.delete()
# Start your loop.
live_notifs_loop.start()
# Command to add Twitch usernames to the json.
#bot.command(name='addtwitch', help='Adds your Twitch to the live notifs.', pass_context=True)
#commands.has_permissions(administrator = True)
async def addtwitch(ctx, twitch_name):
# Opens and reads the json file.
with open('streamers.json', 'r') as file:
streamers = json.loads(file.read())
# Gets the users id that called the command.
user_id = ctx.author.id
# Assigns their given twitch_name to their discord id and adds it to the streamers.json.
streamers[user_id] = twitch_name
# Adds the changes we made to the json file.
with open('streamers.json', 'w') as file:
file.write(json.dumps(streamers))
# Tells the user it worked.
await ctx.send(f"Added {twitch_name} for {ctx.author} to the notifications list.")
ping()
bot.run(os.getenv('token'))
Edit:
Please say if something is not right or you don't understand the question instead of just closing it.
To send the embed in the same message you can use content an example would be:
await channel.send(content=f"`Hey #everyone, {twitch_name} is live! Check it out:" + f"https://www.twitch.tv/{twitch_name}`", embed=twitch_embed)
There would be no change in your check function as the message.content would be the same text message just with an embed as well.
You should really check if the stream has finished either by web scraping or some API instead of checking message content. If the stream finishes 3 hours ago but you only check for 2 streamers there won't be a change unless you have thought of this already.
i wanted to make a bot to discord for delete messages easly. it works 3 months ago but now i got an error " 'Member' object has no attribute 'hasPermission' ". thanks for everyone to share opinion. have a nice day.
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
if message.content.startswith('botcuksil'):
if (message.author.hasPermission('MANAGE_MESSAGES')):
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
It is throwing 'Member' object has no attribute 'hasPermission' this error because 'Member' does not have an attribute named 'hasPermission'. To fix your problem, I have re-written your code and also given some explanation below the code:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = 'botcuk')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Streaming(name="admin biseyler deniyor", url='https://www.youtube.com/watch?v=fw7L7ZO4z_A'))
#client.event # we need to add and check for a client event
async def on_message(): # we need to execute the command when we recieve an message so we define a function called 'async def on_message():'
if message.content.startswith('botcuksil'):
if message.author.guild_permissions.manage_messages: # we need 'author.guild_permissions.(permission)' intead of 'if (message.author.hasPermission('MANAGE_MESSAGES'))'
args = message.content.split(' ')
if len(args) == 2:
if args[1].isdigit():
count = int(args[1]) + 1
deleted = await message.channel.purge(limit = count)
await message.channel.send('{} mesaj silindi'.format(len(deleted)-1))
I have not tested this yet, but according to me, your problem: 'Member' object has no attribute 'hasPermission' should be solved.
What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Summary of what I have done:
I have added a client event (#client.event) and an async function on_message().
What it does is it checks if it is getting an message or not. If it detects a new message in any of the servers it is invited to, it triggers the code in on_message().
As I said: What you have done was message.author.hasPermission('MANAGE_MESSAGES') but message.author has no attribute like hasPermission.
Instead of writing that, we can use message.author.guild_permissions.manage_messages. It checks if the message author's server's permissions include "manage_messages". Hope my solution fixes your problem.
Always happy to help!
-sqd mountains
So I'm making a discord bot for a server that I use and wanted to add a censor feature so that if a user said something in the "bannedWords" list while not in a specific channel (working) it would edit the message to have "[redacted]" in its place. I believe the code itself is working but I get this error message every time I test it. I've tried adding permissions via the Discord Developer Portal (selecting "OAuth2," choosing the "bot" scope, and the manage roles, view channels, send messages, manage messages, read message history, and mention everyone permissions), copied the link and added it to my testing server but it still didn't seem to work along with having the proper permissions via role.
Full Error:
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Me\Desktop\Productive\Programming Projects\Python 3\Other\MyBot\bot.py", line 32, in on_message
await message.edit(content = editedMessage)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\message.py", line 843, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
File "C:\Users\Me\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\http.py", line 241, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
Code
import discord
bot=discord.Client()
#bot.event
async def on_ready():
print('Logged in')
print("Username: %s" % (bot.user.name))
print("Userid: %s" % (bot.user.id))
#bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
bannedWords=['chink','dyke','fag','ook','molest','nig','rape','retard','spic','zipperhead','tranny']
print(str(message))
print(str(message.content))
if "name='no-rules-lol'" not in str(message): #probably a better way to do this but it works
for word in bannedWords:
if word in message.content.lower():
await message.channel.send('{0.author.mention}, you have used a word that is black-listed please read <#754763230169006210> to get a full list of black-listed words'.format(message))
#await message.edit(content = message + 'this has been edited')
editedMessage=str(message.content.replace(word,'[redacted]'))
await message.edit(content = editedMessage)
bot.run(Token)
You cannot edit a message that is not sent by the bot.
Instead, just try deleting the message.
await message.delete()
It is as easy as that.
If you are adding more commands into your bot, you can just add this to your on_message at last:
await bot.process_commands(message)
Thank you.
So modern documentation on the bot.wait_for() coroutine is not super detailed, and I'm having trouble getting it to work with reactions. Would appreciate feedback.
Python 3 with Discord.py
## Test Role Add
#kelutralBot.command(name='testreaction')
async def testReaction(ctx):
member = ctx.message.author
message = await ctx.send("This is a test message.")
emojis = ['\u2642','\u2640','\u2716']
for emoji in emojis:
await message.add_reaction(emoji)
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '\u2642'
try:
reaction, user = await kelutral.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
else:
print(reaction)
male = get(member.guild.roles, name="He/Him")
await member.add_roles(male)
print("Assigned " + member.name + " He/Him pronouns.")
Two things were wrong.
First, don't use Client and Bot in the same command. Bot is sufficient for both.
Second, Unicode Emoji for Discord are treated as '\U000#####', which was the biggest problem.
Once we solved that, everything worked as intended.
The problem here is that you are checking if the person who sent the reaction is the author of the message that contains the message, which is only satisfied by the bot that reacted. Also consider using a role ID instead (server settings > roles > left click role > right click role > copy ID). You also want to be consistent with kelutral or kelutral Bot throughout the command.
#kelutralBot.command(name='testreaction')
async def testReaction(ctx):
member = ctx.message.author
message = await ctx.send("This is a test message.")
emojis = ['\u2642','\u2640','\u2716']
for emoji in emojis:
await message.add_reaction(emoji)
def check(reaction, user):
return user == member and str(reaction.emoji) == '\u2642' # check against the member who sent the command, not the author of the message
try:
reaction, user = await kelutralBot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send("Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.")
else:
print(reaction)
male = ctx.message.guild.get_role(ROLE_ID_GOES_HERE) # put your role ID here #
await member.add_roles(male)
print(f"Assigned {member.name} He/Him pronouns.")
Keep in mind your code only works for the "male" role, you have to implement a different check function to use it for everything.