I am trying to code a bot that will simultaneously print new messages in a server to console and for the user to be able to send messages to the server at the same time.
import discord
from asyncio import run
from threading import Thread
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
async def p():
ap = await client.fetch_channel(1234567890)
return ap
main_guild = run(p())
def log_msg(msge,date):
with open('log.txt','a') as f:
f.write(msge + '\n' + date)
f.close()
async def send_a_message():
while True:
await main_guild.send(input('Send message: '))
#client.event
async def on_message(message):
base_msg = str(message.author)+': '+str(message.channel.name)+': '+str(message.content)
date = str(message.created_at)
if len(message.attachments) == 0:
print(base_msg)
log_msg(base_msg,date)
return
for i in range(len(message.attachments)):
base_msg += '\n'+(message.attachments[i]).url
log_msg(base_msg,date)
t = Thread(target=lambda:run(send_a_message()))
t.start()
try:
client.run('#######################')
except discord.errors.HTTPException:
from os import system
system('kill 1')
However, I get a strange error:
Traceback (most recent call last):
File "main.py", line 13, in <module>
main_guild = run(p())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 10, in p
ap = await client.fetch_channel(999141783709679668)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/client.py", line 1824, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/home/runner/RandomRepl/venv/lib/python3.10/site-packages/discord/http.py", line 604, in request
if not self._global_over.is_set():
AttributeError: '_MissingSentinel' object has no attribute 'is_set'
What is causing this and how do I fix this?
Thank you.
To get the channel you are using the client. But you are trying to get the channel before actually running the client, so you can't get the channel.
You have to first run the client and then get the channel. A possibility would be to use the on_ready event (called after client.run('...')) to get the channel.
Here is an example code you can start working with:
import discord
client = discord.Client(intents=discord.Intents.all())
main_guild = None
#client.event
async def on_ready():
global main_guild
await client.wait_until_ready()
main_guild = client.get_channel(1234567890)
print('Connected')
#client.event
async def on_message(message):
if message.author.id == client.user.id: return
if message.channel.type == discord.ChannelType.private: channel = 'DM'
else: channel = message.channel.name
base_msg = f'{message.author}: {channel}: {message.content}'
await main_guild.send(base_msg)
client.run('#######################')
Related
I keep getting this error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "bot.py", line 191, in on_command_error
raise error
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: cooldown is a required argument that is missing.
Please help me its saying that here is my code
import discord
import json
import requests
import time
from discord.ext import commands
from discord.ext.commands import cooldown
from datetime import datetime, timedelta
on_cooldown = {}
client = commands.Bot(command_prefix = "!")
client.remove_command("help")
async def get_user_data():
with open("account.json","r") as f:
users = json.load(f)
return users
#client.event
async def on_ready():
print("Bot is ready")
print('Connected to bot: {}'.format(client.user.name))
print('Bot ID: {}'.format(client.user.id))
await client.change_presence(activity=discord.Game(name="Dwayne is protecting" + str(len(client.guilds)) + "Eggplants ", type=0))
#help command
#client.command(pass_context=True, aliases=['Help'])
async def help(ctx):
embed=discord.Embed(title="Help", description='Bot prefix = ?', color=0x7a0000)
embed.add_field(name="Spammers", value="!post <number> <message> <quantity>\n!plan", inline=True)
embed.add_field(name="Admin", value="!createa <User ID> <ExpDate> <cooldown> (Y-M-D)\n!bana <User ID> <Reason+Reason>\n?purge <amount>\n!ban <user> <reason>\n!unban <user>", inline=False)
embed.set_footer(text="Dwayne Bot")
await ctx.send(embed=embed)
#client.command()
async def post(ctx, To, message, amount):
users = await get_user_data()
if str(ctx.author.id) in users:
if users[str(ctx.author.id)]['Banned'] == 'N':
timeleft = datetime.strptime(users[str(ctx.author.id)]['expDate'],'%Y-%m-%d') - datetime.now()
if timeleft.days <= 0:
em = discord.Embed(color=0x7a0000, description="Sorry your plan on this tool has expired")
await ctx.send(embed=em)
else:
move_cooldown = users[str(ctx.author.id)]["cooldown"]
try:
last_move = datetime.now() - on_cooldown[ctx.author.id]
except KeyError:
last_move = None
on_cooldown[ctx.author.id] = datetime.now()
if last_move is None or last_move.seconds > move_cooldown:
on_cooldown[ctx.author.id] = datetime.now()
message = message.replace('+',' ')
requests.get(f'http://45.61.54.145/api.php?key=CRzQHsKuHpF3x2M9GFrR&to={To}&message={message}&amount={amount}')
await ctx.send('Check Messages')
await ctx.message.delete()
author = ctx.message.author
test_e = discord.Embed(colour = discord.Colour.from_rgb(166, 245, 255))
test_e.set_author(name="Hello thank you for using our spammer!")
test_e.add_field(name="Request", value="Your request to spam this number has been successful!", inline=False)
test_e.add_field(name="Refresh", value="You may use this command again in 5 minutes this is to keep our spammer less laggy!")
await author.send(embed=test_e)
else:
embed = discord.Embed(color=0x7a0000, description="You're Cooldown Is Still Active!")
await ctx.send(embed=embed)
else:
embed=discord.Embed(title=f"{ctx.author.name}", color=0x7a0000)
embed.add_field(name="User Banned", value=f"Banned: Yes\nBannedOn: {users[str(ctx.author.id)]['BannedOn']}\nBannedBy: {users[str(ctx.author.id)]['BannedBy']}\nBannedReason: {users[str(ctx.author.id)]['BannedReason']}")
embed.set_footer(text="madeby: toxic")
await ctx.send(embed=embed)
else:
embed = discord.Embed(color=0x7a0000, description=f"Sorry you don't have a plan on this tool")
await ctx.send(embed=embed)
In discord.py rewrite (above version v1.0+) pass_context has been removed from commands.
https://discordpy.readthedocs.io/en/stable/migrating.html#context-changes
Try removing that from the help command.
I am a beginner at discord.py and can't understand why my bot is not correctly. I use VS Code IDE to code and execute my bot through the Command Prompt or Repl.it. I am making a bot to chant some lines 24/7 in my discord server.
When I try to run my bot and write "ch!start" in my server, it gives me this error:
Traceback (most recent call last):
File "...\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "...\bot.py", line 36, in on_message
await chant()
File "...\bot.py", line 17, in chant
if ss == 'not chanting':
UnboundLocalError: local variable 'ss' referenced before assignment
Why is this happening, and how do I fix it?
Here is my code:
# bot.py
#disabled from keep_alive import keep_alive
import discord
import os
import time
client = discord.Client()
ss = 'not chanting'
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
print('I am ready to chant.')
async def chant():
if ss == 'not chanting':
ss = chanting
print('changed not chanting to chanting')
elif ss == 'chanting':
ss = 'not chanting'
print('changed chanting to not chanting')
#client.event
async def on_message(message):
msg = message.content
sendmsg = message.channel.send
author = message.author
if msg == 'ch!help':
await sendmsg('**24/7 Chanter**\nch!help - gives a list of commands I can do\nch!start - starts chanting in the specified channel\nch!stop - stops chanting')
if msg == 'ch!start':
if ss == 'not chanting':
await chant()
await sendmsg('Ok. Chanting now.')
await sendmsg('(This message triggers the code to chant.) reference')
elif ss == 'chanting':
await sendmsg('I **am** chanting!')
if msg == 'ch!stop':
if ss == 'chanting':
await chant()
await sendmsg('Ok. Stopping chanting...')
await sendmsg('Please wait...')
elif ss == 'not chanting':
await sendmsg('I **am not** chanting!')
if msg.endswith('reference'):
await sendmsg('passed test 1')
if author == client.user:
await sendmsg('passed test 2')
if ss == 'chanting':
await sendmsg('passed test 3')
await asyncio.time(4)
await sendmsg('passed test 4')
await sendmsg('(MSG)')
await asyncio.time(1)
await sendmsg('(MSG)')
await asyncio.time(3)
await sendmsg('(MSG)')
await asyncio.time(7)
await sendmsg('(MSG)')
await asyncio.time(9)
await sendmsg('(MSG)')
await asyncio.time(5)
await sendmsg('(MSG) reference')
client.run('no token 4 u')
There are multiple errors. One is in async def chanting(): Try ss = 'chanting', not ss = chanting. Also, ss is not a global variable. You need to make it one. View comments for how to do that.
Everything is set up right, the bot is in the discord, connected, etc.
This code:
import discord
import random
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
color2 = "%06x" % random.randint(0, 0xFFFFFF)
print(color2)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!randomcolor'):
server = client.get_guild('')
role = "Rainbow tester"
color = "%06x" % random.randint(0, 0xFFFFFF)
await role.edit(server=server, role=role, colour=color)
await message.channel.send('Trying that...')
client.run('TOKEN')
Gives this error:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 22, in on_message
await role.edit(server=server, role=role, colour=color)
AttributeError: 'str' object has no attribute 'edit'
If anyone can find where I went wrong or any errors I've made, please help!
I would use the discord.Color.random() function for that as it looks like the problem occurs in your color-line.
Re-write your code to the following:
from discord.utils import get
if message.content.startswith('!randomcolor'):
guild = client.get_guild(GuildID)
role = get(guild.roles, name="Rainbow tester") # Get the role
color = discord.Color.random() # Choose a random color
await role.edit(server=guild, role=role, colour=color)
await message.channel.send('Trying that...')
What did we do?
Imported from discord.utils import get
Changed the way we get the role: (get(guild.roles, name="Rainbow tester") or role = discord.utils.get(message.guild.roles, name='Rainbow tester')
Used the discord.Color.random() function to choose a random color
Try:
role = discord.utils.get(message.guild.roles, name='Rainbow tester')
import discord
from discord.ext import commands, tasks
import datetime
import requests
import time
from bs4 import BeautifulSoup
client = discord.Client()
r = requests.get("https://www.worldometers.info/coronavirus/country/italy/")
s = BeautifulSoup(r.text, "html.parser")
data = s.find_all("div",class_ = "maincounter-number")
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#tasks.loop(seconds=50.0)
async def covid():
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
channel = bot.get_guild(guild).get_channel(channel)
await message.channel.send("casi di coronavirus in italia: \ncasi totali: " +
data[0].text.strip()
+ "\nmorti totali: " + data[1].text.strip()
+ "\nguariti totali: " + data[2].text.strip())
#covid.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
#covid.after_loop
async def post_loop(self):
if self.covid.failed():
import traceback
error = self.covid.get_task().exception()
traceback.print_exception(type(error), error, error.__traceback__)
client.run('token)
basically this code checks if it is a specified time and if it is it sends a message with the covid data of italy but it doesn't work and doesn't return anything i tried even adding an error handler (traceback) and doesn't do anything the only output i have is from async def on_ready()
so i tried this:
data = ''
#tasks.loop(seconds=50.0)
async def covid(ctx):
global data
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
data = "casi di coronavirus in italia: \ncasi totali: " +
data[0].text.strip() + "\nmorti totali: " + data[1].text.strip()
return data
#covid.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
#client.command()
async def get_covid(ctx):
global data
await ctx.send(data)
but i don't get any output and if i add #client.command() before async def covid
it gives me this error:
Traceback (most recent call last):
File "C:\Users\danie\OneDrive\Desktop\test.py", line 26, in
async def covid(ctx):
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site- packages\discord\ext\commands\core.py", line 1162, in decorator
result = command(*args, **kwargs)(func)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 1317, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\danie\AppData\Local\Programs\Python\Python38\lib\site- packages\discord\ext\commands\core.py", line 210, in init
raise TypeError('Callback must be a coroutine.')
TypeError: Callback must be a coroutine.
>>>
You need to add a context in the function and #bot.command() decorator followed by your instance.
Likewise:
#client.command()
async def test(ctx):
await ctx.send('PASSED')
a message is an event and you need to add a proper listener for it to work. You don't need to use this event unless you need the text data.
In your case, you are sending the data directly from your COVID-19 function which doesn't do anything since the message is not defined.
It would be as:
#STORE THE VALUE OF COVID INSIDE DATA VARIABLE.
data = ''
#tasks.loop(seconds=50.0)
async def covid():
global data
x = datetime.datetime.now()
d = x.strftime("%M")
if d == "21":
#Assign the value to DATA VARIABLE.
data = "casi di coronavirus in italia: \ncasi totali: " + data[0].text.strip() + "\nmorti totali: " + data[1].text.strip()
#Return the MODIFIED Data
return data
Now send the data with this function.
#client.command()
async def get_covid(ctx):
global data
await ctx.send(data)
Also, You defined the client wrongly. client = discord.Client()
It should be as:
# change '!' to any prefix you would like to use.
client = commands.Bot(command_prefix ='!')
I have been trying to help a friend fix his discord bot, but I'm stumped on the solution.
from discord.ext import commands
import bs4
import requests
import time
import lxml
adminkey = "CheeseIsTheBest"
keys = open('keys.txt', 'w')
TOKEN = "token goes here"
client = commands.Bot(command_prefix = "!")
client.remove_command('help')
#client.event
async def on_ready():
print("Locked And Loaded Mr. DarkKnight")
#client.command(name='ping')
async def ping(ctx):
await ctx.send('pong')
#client.command()
async def addkey(ctx, key):
if str(ctx.author) == "ironkey#6969" or str(ctx.author) == "ZERO#2020":
with open('keys.txt', 'r+') as file :
file.write(str(key + "\n"))
file.close()
await ctx.send('key added')
else:
await ctx.send('your not authorized to preform this action ' + str(ctx.author))
#client.command()
async def redeemkey(ctx, key):
with open('keys.txt', 'r+') as file:
for line in file:
if str(key.strip()) == str(line.strip()):
with open('keys.txt', 'w') as file:
keyfile = keyfile.replace(str(key), key + " X")
file.write(keyfile)
file.close()
await ctx.send('key redeemed!')
else:
await ctx.send('This key has already been used')
#client.command()
async def unbind(ctx, *, member):
role = discord.utils.get(ctx.guild.roles, name='authenticated')
await client.remove_roles(member, role)
#client.command(aliases=['inv'])
async def invite(ctx):
await ctx.send('https://discordapp.com/api/oauth2/authorize?client_id=645664026160005129&permissions=8&scope=bot')
#client.command()
async def help(ctx):
embed = discord.Embed(color=discord.Color.dark_blue())
embed.set_author(name="Cheese Auth Help Menu", icon_url="")
embed.add_field(name=".ping", value="a simple fun command! usage : .ping")
embed.add_field(name=".invite", value="also used with the command inv, this command will get you an invite link so you can add this bot to your server! usage: .invite")
await ctx.send(embed=embed)
client.run(TOKEN)
Every time I try to redeem the key I added, I get this error:
Ignoring exception in command redeemkey:
Traceback (most recent call last):
File "C:\Users\seang\AppData\Local\Programs\Python\Python36-32\lib\site-packages\discord\ext\commands\core.py", line 79,
in wrapped ret = await coro(*args, **kwargs)
File "C:\Users\seang\Downloads\Bot_for_DarkKnight1-_Copy.py", line 41,
in redeemkey keyfile = keyfile.replace(str(key + X))
UnboundLocalError: local variable 'keyfile' referenced before assignment.
From your code i noticed that keyfile.replace is the problem. Variable keyfile is not assigned or declared (defined) yet.You are reading a file line by line in variable line so I think your code should be
keyfile = line.replace(str(key), key + " X")
The error comes from this line:
keyfile = keyfile.replace(str(key), key + " X")
You're trying to make a new value called 'keyfile', but it relies on information which comes from 'keyfile', which doesn't exist yet.