Discord.py warning [closed] - discord

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I've been working on a moderator discord bot. Made all the command except the warn command. Can anyone help me to make a warn command.
If the member (with manage member permission) types ?warn #user reason the bot will save the warning in a file
And if the user says ?warnings #user the bot will show the warnings of the user also an unwarn command like when the user says ?unwarn #user bot should be able to unwarn the specified user.

Did you mean this?
def save_warn(ctx, member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] += 1
with open('warns.json', 'w') as f:
json.dump(warns, f)
def remove_warn(ctx, member: discord.Member, amount: int):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)] -= amount
with open('warns.json', 'w') as f:
json.dump(warns, f)
def warns_check(member: discord.Member):
with open('warns.json', 'r') as f:
warns = json.load(f)
warns[str(member.id)]
return warns
#bot.command()
#commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
save_warn(ctx, member)
dm = await bot.fetch_user(member.id)
em=discord.Embed(title="Warning", description=f"Server: {ctx.guild.id}\nReason: {reason}"
await dm.send(embed=em)
#bot.command()
#commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
warns = warns_check(member)
await ctx.send(f"{member.name} has {warns} warnings.")
#bot.command()
#commands.has_permissions(kick_members=True)
async def rmwarn(ctx, member: discord.Member, amount: int):
remove_warn(ctx, member, amount)
await ctx.send(f"Removed {amount} warnings from {member.name}!")

Related

Whats causing this error? TypeError: Client.__init__() missing 1 required keyword-only argument: 'intents'

Whats causing this error?
TypeError: Client.init() missing 1 required keyword-only argument: 'intents'
Here is my code below
## install discord.py
## py -3 -m pip install -U discord.py
## install requests
## py -3 -m pip install -U requests
## install qbittorrent-api
## py -3 -m pip install -U qbittorrent-api
import discord
from discord.ext import commands
import requests
import qbittorrentapi
def filterBy(TorrentInfo,filterType):
if TorrentInfo[1]==filterType or filterType=="all":
return True
else:
return False
def filterList(FullList,filterType):
FilteredList=[]
for i in range(len(FullList)):
if filterBy(FullList[i],filterType):
FilteredList.append(FullList[i])
SortedList=[]
for i in range(len(FilteredList)):
if FilteredList[i][2]!="100%":
SortedList.append(FilteredList[i])
SortedList.sort(key=lambda x:float(x[2][:-1]),reverse=True)
for i in range(len(FilteredList)):
if FilteredList[i][2]=="100%":
SortedList.append(FilteredList[i])
return SortedList
def renameStates(FullList):
completedList=["uploading","pausedUP","checkingUP","stalledUP","forcedUP"]
downloadingList=["downloading"]
missingList=["missingFiles"]
stalledList=["stalledDL"]
metaList=["metaDL"]
queuedList=["queuedDL"]
pausedList=["pausedDL"]
for i in range(len(FullList)):
if FullList[i][3] in completedList:
FullList[i][3]=StatusList[0]
elif FullList[i][3] in downloadingList:
FullList[i][3]=StatusList[1]
elif FullList[i][3] in missingList:
FullList[i][3]=StatusList[2]
elif FullList[i][3] in stalledList:
FullList[i][3]=StatusList[3]
elif FullList[i][3] in metaList:
FullList[i][3]=StatusList[4]
elif FullList[i][3] in queuedList:
FullList[i][3]=StatusList[5]
elif FullList[i][3] in pausedList:
FullList[i][3]=StatusList[6]
else:
FullList[i][3]=StatusList[7]
return FullList
def findCompleted(FullList):
CompletedList=[]
for i in range(len(FullList)):
if FullList[i][3]==StatusList[0]: #Completed
CompletedList.append(FullList[i])
return CompletedList
def findDownloading(FullList):
DownloadingList=[]
for i in range(len(FullList)):
if FullList[i][3]==StatusList[1]: #Downloading
DownloadingList.append(FullList[i])
elif FullList[i][3]==StatusList[3]: #Stalled
DownloadingList.append(FullList[i])
elif FullList[i][3]==StatusList[4]: #DownloadingMeta
DownloadingList.append(FullList[i])
elif FullList[i][3]==StatusList[5]: #Queued
DownloadingList.append(FullList[i])
elif FullList[i][3]==StatusList[6]: #Paused
DownloadingList.append(FullList[i])
return DownloadingList
def convertToDiscord(InfoList):
if not InfoList:
return NothingDownloading
maxCharsDiscord=1700
FinalList=[]
indexRange=[2,3,4,0]
for i in range(len(InfoList)):
FinalList.append([])
for j in range(len(indexRange)):
if InfoList[i][indexRange[j]]!="inf":
FinalList[i].append(InfoList[i][indexRange[j]])
StringListTwo=convertToString(FinalList)
StringList=convertToString(FinalList)
currentLength=len(StringList)
currentMsg=[]
while currentLength>0:
maxLength=StringList[0:maxCharsDiscord].count('\n')
numChars=findNth(StringList,'\n',maxLength)
if(StringList[numChars+1:-1].count('\n'))==0:
currentMsg.append(StringList[:])
else:
currentMsg.append(StringList[0:numChars])
StringList=StringList[numChars+1:-1]
currentLength=currentLength-maxCharsDiscord
return currentMsg
def findNth(String,Substring,Occurence):
val = -1
for i in range(0, Occurence):
val = String.find(Substring, val + 1)
return val
def convertToString(nonStrList):
StringList=str(nonStrList)
if StringList.find(ListSeparator)==-1:
StringList=StringList.replace("'], ['","\n\n")
StringList=StringList.replace("']]","")
StringList=StringList.replace("[['","")
StringList=StringList.replace("', '",ListSeparator)
else:
StringList=StringList.replace("', '","\n\n")
StringList=StringList.replace("']","")
StringList=StringList.replace("['","")
return StringList
def printMessages(DiscordLists):
if DiscordList!=NothingDownloading:
for i in range(len(DiscordLists)):
print(convertToString(DiscordLists[i]))
print("------------------------------------------------")
else:
print(NothingDownloading)
print("------------------------------------------------")
StatusList = ["Completed","Downloading","Files missing","Stalled","Attempting to start","Queued","Paused","Unknown status"]
ListSeparator = ", "
NothingDownloading = "Nothing is downloading! Why not request something?"
DownloadingStatus = "downloading"
CompleteStatus = "completed"
#############################
## ENTER YOUR DETAILS HERE ##
#############################
botChannel = "BOT CHANNEL" ## ID CHANNEL OF THE CHANNEL FOR THE BOT TO LISTEN TO ##
tvCategory = "tv-sonarr" ## CATEGORY IN QBIT FOR TV SHOWS ##
movieCategory = "radarr" ## CATEGORY IN QBIT FOR MOVIES ##
qbt_client = qbittorrentapi.Client(host='localhost', port=8080, username='admin', password='password') ## QBIT WEB LOGIN DETAILS ##
TOKEN = "BOT SECRET" ## DISCORD BOT SECRET ##
#############################
#############################
#############################
# the Client will automatically acquire/maintain a logged in state in line with any request.
# therefore, this is not necessary; however, you may want to test the provided login credentials.
try:
qbt_client.auth_log_in()
except qbittorrentapi.LoginFailed as e:
print(e)
def updateTorrentList():
counter = 0
TorrentList=[]
for torrent in qbt_client.torrents_info():
TempList=[]
TempList.append(torrent.name)
TempList.append(torrent.category)
TempList.append(str(round(torrent.progress*100,2))+"%")
TempList.append(torrent.state)
TempList.append(convertTime(torrent.eta))
TorrentList.append(TempList)
counter=counter+1
return TorrentList
def convertTime(seconds):
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),)
if seconds!=8640000:
result = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return 'ETA: '+', '.join(result[:])
else:
return "inf"
def updateAll(category,status="all"):
TorrentList=updateTorrentList()
FilteredList = filterList(TorrentList,category)
FinalList=renameStates(FilteredList)
if status==DownloadingStatus:
FinalList=findDownloading(FinalList)
elif status==CompleteStatus:
FinalList=findCompleted(FinalList)
DiscordList=convertToDiscord(FinalList)
return DiscordList
print("------------------------------------------------")
print("starting Discord...")
client = discord.Client()
prefix = "$"
bot=commands.Bot(command_prefix=prefix)
## BOT VERSION ##
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
print("------------------------------------------------")
#bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
#bot.command(
help = "Use this to see the status of what's currently downloading."+"\n"+"If you want to get fancy, you can search for movies/tv shows specifically by type $status movies or $status tv."+"\n"+"You can also see what's completed by doing $status completed, or $status all to see everything."+"\n"+"Finally, you can combine these (like $status tv completed) to only see completed tv shows."+"\n"+"(tip: you can see everything by typing $status all)",
brief = "Use this to see what's currently downloading"
)
async def status(ctx, *args):
channelID=ctx.message.channel.id
if botChannel==channelID:
def not_pinned(message):
return not message.pinned
await ctx.message.channel.purge(check=not_pinned)
if "all" in args:
updateStatus="all"
elif "completed" in args:
updateStatus=CompleteStatus
else:
updateStatus=DownloadingStatus
if "movies" in args:
Category=movieCategory
elif "tv" in args:
Category=tvCategory
else:
Category="all"
DiscordList=updateAll(Category,updateStatus)
if DiscordList!=NothingDownloading:
for i in range(len(DiscordList)):
await ctx.channel.send(DiscordList[i])
else:
await ctx.channel.send(NothingDownloading)
bot.run(TOKEN)
can't get my discordbot to run. it worked in the past, but stopped working. it's job is to allow the user to check the status of a requested media download. any help would be greatly appreciated.
versions of discord.py 2.0 and above require the argument intents.
prefix = "$"
bot=commands.Bot(command_prefix=prefix, intents=discord.Intents.all())
Adding intents is must for the bot to work.
you can learn more about intents at https://discordpy.readthedocs.io/en/latest/intents.html?highlight=intents

Stop 2 consecutive uses discord.py

I am making a discord bot in which an auction could take place.So I want someone to bid only once unless someone bids after him/her.
`async def bid(ctx):
embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')
await ctx.send(embed=embed1)
`
That's what I have so far made.
You could put the author id in a variable:
bidderid = 0 #this will reset whenever your bot restarts
#client.command()
async def bid(ctx):
global bidderid
if ctx.author.id != bidderid: #if it is not the same bidder
bidderid = ctx.author.id
embed1=discord.Embed(description= f'Bid has been placed by {ctx.author}', title='bid placed')
await ctx.send(embed=embed1)
else: #if it is the same bidder
await ctx.send('You cannot bid twice in a row!') #replace with whatever message
note: It doesn't have to be the id, you could store ctx.author instead, idea is the same

How do i make my discord.py bot go through a text file and if a user says a word in that file it will delete that message + how to make uptime command

I want my discord.py bot to go through a text file and if a user says a word in that file it will delete that message
elif msg.content == '***':
await msg.channel.send("Dont curse")
await msg.delete()
that is my code but i want to replace *** with a text document
And also another question i have some issues with an uptime command
async def on_ready():
print("Bot is running")
activity = discord.Game(name="!test", type=3)
await client.change_presence(status=discord.Status.idle, activity=activity)
channel = client.get_channel(944665750453497886)
myid = '<#516236429689618467>'
await channel.send("I am online "+myid)
#Uptime code starts
global startdate
startdate = datetime.now()
#client.command()
async def uptime(ctx):
now = datetime.now()
uptime = startdate - now
uptime = uptime.strftime('%d/%h/%M')
await ctx.send(f'Uptime: {uptime}')

Getting the users total invites in Discord.py

I am trying to add a command to my bot which replies with the total people the user has invited to the server
My code:
if message.content.startswith('!invites'):
totalInvites = message.guild.invites
await message.channel.send("You have invited: " + totalInvites + " members to the server")
The bot replies with:
You have invited: <bound method Guild.invites of <Guild id=server_id_goes_here name='my bot' shard_id=None chunked=True member_count=12>> members to the server
What is it that I am doing wrong?
You've almost got the right idea!
on_message event usage:
#bot.event
async def on_message(message):
if message.content.startswith('!invites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You've invited {totalInvites}
member{'' if totalInvites == 1 else 's'} to the server!")
Command decorator usage:
#bot.command()
async def invites(ctx):
totalInvites = 0
for i in await ctx.guild.invites():
if i.inviter == ctx.author:
totalInvites += i.uses
await ctx.send(f"You've invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the server!")
First I'm iterating through each invite in the guild, checking who created each one. If the creator of the invite matches the user that executed the command, it then adds the number of times that invite has been used, to a running total.
You don't need to include the {'' if totalInvites == 1 else 's'}, that's just for the odd case that they've invited 1 person (turns member into the plural - members).
References:
Guild.invites - the code originally didn't work because I forgot this was a coroutine (had to be called () and awaited).
Invite.uses
Invite.inviter
commands.command()
F-strings Python 3.6+

(Discord.py) Send a dm or is to all members of all servers

I begin the dev for 2 days and i want to create a command in the dm of the bot ">
#bot.event
async def on_message(message):
if message.content.startswith('><dmall'):
name = message.content.split(" ")[1]
if(name == "all"):
for member in message.guild.members:
try:
await member.send("test")
except discord.Forbidden:
print("[DM]" + name + "à bloqué ses dm")
else:
member = discord.utils.get(message.guild.members, name=name)
NOTE: PLEASE DO NOT ABUSE THIS, IT IS A BANNABLE OFFENSE ON DISCORD'S TOS
# an alternative to putting your commands in an on_message event:
#bot.command()
async def dmall(ctx):
for m in bot.get_all_members():
await m.send("Hello! This is a DM :)")
print("Done!")
# error handler
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.Forbidden):
print(f"[DM] {ctx.author} has DMs disabled.")
else:
print(error)
References:
Client.get_all_members()
discord.on_command_error()
Exceptions

Resources