I am creating a bot that creates a backup of discord guilds in mysql. (Basically it allows me to make a website that is an extension of the discord channel.)
I am going to be downloading and saving attachments in then (guild,channel,user) folder path so I can query them on the website.
Also I am going to be purging inactive users by checking to see who is active withing the last 24 hours, last week, etc.
Anyway so I am trying to check to see if a message has an attachment using the following script,
#client.event
def on_message(message):
msg = str(message.content)
channel = str(message.channel)
guild = str(message.guild)
author=str(message.author)
if checkfordb(guild) == 1:
if checkfortable(channel,guild) == 1:
addmsg(channel,guild,msg,author)
else:
createtb(channel,guild)
addmsg(channel,guild,msg,author)
else:
createdb(guild)
createtb(channel,guild)
addmsg(channel,guild,msg,author)
if message.Attachment.size > 0:
print("There is an attachment")
else:
print("There is no attachment")
The problem is that when I run this script I get the following error,
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "bot2.py", line 145, in on_message
if message.Attachment.size > 0:
AttributeError: 'Message' object has no attribute 'Attachment'
So I checked the documentation and sure enough despite tons of other people saying they are using it there is no attachment attribute for message. The documentation under attachment says you can use class discord.attachment. So I looked at the classes and I see no way to pull an attachment when it is posted. Does anyone have any ideas on how to do this?
Any and all help is appreciated.
The correct attribute name is Message.attachments as Patrick Haugh suggested. You could use the len() function on that to get the "size" of it since it's just a normal python list of discord.Attachment objects.
if message.attachments:
Simple as that!
Related
I'm running the following code, which is failing
stripe_card_response = customer.sources.create(source=source)
The response that I get back is as follows:
File "/opt/python/run/venv/local/lib/python3.6/site-packages/stripe/stripe_object.py", line 50, in __getattr__
raise AttributeError(*err.args)
AttributeError: sources
Within my python code, I would I capture that error associated with this failure so that I can print it?
Thanks!
I think you might be using an older syntax that is no longer supported. To attach a source to a Customer you'd do:
customer = stripe.Customer.modify(customer.id, source=source)
So I'm trying to make a timed function for my Discord bot with python.
So my function is as follows:
async def checkday(ctx):
while(True):
"code yada yada"
if true:
await ctx.send("hello")
await asyncio.sleep(X)
and at the bottom:
bot.loop.create_task(checkday())
However, I either get this error:
Traceback (most recent call last):
File "C:\Users\philk\Desktop\Discord Bot\testrevbot.py", line 374, in <module>
bot.loop.create_task(checkday())
TypeError: checkday() missing 1 required positional argument: 'ctx'
So I'm assuming there is an argument I'm missing here:
bot.loop.create_task(checkday())
How would I be able to fix this? I'm using Rewrite I believe, so is there a way to send messages without Context?
EDIT: I want to, for example, run the loop in checkday() every 12 hours, and if conditions are met, then to send a message.
"https://github.com/Rapptz/discord.py/blob/rewrite/examples/background_task.py" doesn't appear to work for me.
If you are doing this in a cog, you are most probably missing self as the first argument.
I am trying to update the firmware of a controller through a serial interface. To do this, I must send a reboot message to the controller (no problem there) and then send another message (the character 'w') THE MOMENT it starts up so that it may start up in write mode. This is easily done with the minicom utility by pressing w continuously while the device restarts.
I want to achieve this functionality using python code instead, but I can't figure out how to send a message until the device is up without throwing exceptions (since the device is not connected).
This is what I have tried, but it does not work (with pyserial):
def send_w(serial_port, baud_rate):
msgw = "w_"
ans = ""
ser = serial.Serial(port=serial_port, baudrate=baud_rate,timeout = 10)
ser.write(msgw)
ans = ser.read(24)
ser.close()
print(ans)
return ans
def set_firmware_version(serial_port, baud_rate):
s = ""
try:
with serial.Serial(serial_port,baud_rate,timeout=1) as ser:
msgr = "%reset "+sk+"_"
ser.write(msgr)
ser.close()
print("reset")
except (IOError) as e:
print("Error in: set_firmware_version")
print(e)
return s
time.sleep(1)
send_w(serial_port, baud_rate)
set_firmware_version(sp,br)
This gives the following error:
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
I also tried sending the messages in a loop with a short timeout, but had the same problem. Is there any way to send a message continuously and disregard exceptions if the device is not found?
Any help will be greatly appreciated.
Full Traceback:
Traceback (most recent call last):
File "mc_config.py", line 69, in <module>
set_firmware_version(sp,br)
File "mc_config.py", line 64, in set_firmware_version
send_w(serial_port, baud_rate)
File "mc_config.py", line 46, in send_w
ans = ser.read(24)
File "/home/avidbots/.local/lib/python2.7/site-packages/serial/serialposix.py", line 501, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
(I am using ubuntu 16.04 and python 3)
What if you put the excepting code into a try and then catch the exception with an except serial.serialutil.SerialException {...} block?
Clearly there's a significant window of time to submit the w ( otherwise the "press w" method wouldn't often work.) Your requirement, then, would be to retry only the part of the code that's absolutely necessary to send the w, so that you send it quickly enough to "catch" the system in its bootup state. Since the backtrace shows that the exceptions occurs in send_w, then you can add try/except blocks and a while loop around what is now one line at the end of set_firmware_version.
Instead of just this:
send_w(serial_port, baud_rate)
Something like this might solve the problem:
while True:
try:
send_w(serial_port, baud_rate)
break
except serial.serialutil.SerialException:
pass # retry
You may need to change your imports to expose that exception, fyi. And you may need to consider whether you're catching too many possible exceptions - it's possible that exception might also represent other errors that shouldn't be retried. You might also need to add a small sleep time there - this is essentially a busy wait loop (https://en.wikipedia.org/wiki/Busy_waiting).
Does anyone know why this doesn't work?
Instead of printing the solution, it produces this error:
Traceback (most recent call last):
File "C:\Program Files\Python34\lib\tkinter__init__.py", line 1533,
in call return self.func(*args)
TypeError: solution1_s() missing 1 required positional argument: 'sol_s1'
solutions_s={
"sol_s1":"if this is happeing to you, there is a bug in the software. call up your supplier and they will try and troubleshoot the phone. make sure you have all the latest updates installed",
"sol_s2":"these are all signs of a virus. the deleting of applications is virus munching on your data, and pop ups on your scren is also a virus symptom. immiditely use your antivirus to look for the problem or take it to a repair shop where they can delete the virus",
"sol_app":"check if you have enogh storage on your device, if you dont and that was the problem, then see if you can get a storage upgrade. However, if it isnt there is a good chance you have a virus on your phone. scan your phone with an antivirus, or let your local repair shop do it",
"sol_pop":"if the pop ups are on a web browser, this is normal. try getting an ad blocker if it is bothering you, but do not click on them. however, if it is happening on the main screen, you have contracted a virus. use your antivirus orget it fixed at a repair shop",
"sol_s3":"this is another sign of a software fault. the only one who can fix this is your supplier. contact them as soon as possible"}
def solution1_s(sol_s1):
label20=Label(screen,text=solutions_s[sol_s1])
label20.pack()
sys.exit()
def solution2_s(sol_s2):
label22=Label(screen,text=solutions_s[sol_s2])
label22.pack()
sys.exit()
def solution_app(sol_app):
label23=Label(screen,text=solutions_s[sol_app])
label23.pack()
sys.exit()
def solution_pop(sol_pop):
label24=Label(screen,text=solutions_s[sol_pop])
label24.pack()
sys.exit()
def solution3_s(sol_s3):
label26=Label(screen,text=solutions_s[sol_s3])
label26.pack()
sys.exit()
When you put a variable in the function header like this:
def solution1_s(sol_s1):
Python expects that you pass it an argument, which can be anything, and names it sol_s1 within the scope of that function.
However, you appear to want to look up the key sol_s1 in the dictionary solutions_s, which you have declared in your script, instead.
Try this instead:
def solution1_s():
label20=Label(screen,text=solutions_s['sol_s1'])
label20.pack()
sys.exit()
Here's some reading material with in-depth discussion on scopes and dicts:
Scopes
Dictionaries
Here is my code:
from robobrowser import browser
url = 'http://diesel.elcat.kg/index.php?act=Login&CODE=00'
url3 = 'http://diesel.elcat.kg/index.php?act=post&do=reply_post&f=178&t=233500064'
m = browser.RoboBrowser()
m.open(url)
# SIGNING IN(form1)
form1 = m.get_form(action='https://diesel.elcat.kg/index.php?act=Login&CODE=01')
form1['UserName'].value = 'Username'
form1['PassWord'].value = 'Password'
m.submit_form(form1)
# FINISHED SIGNING IN(everything worked)
# GOING TO THE PAGE WHERE FORM IS LOCATED
m.open(url3)
# Can't submit this form
form2 = m.get_form(action="http://diesel.elcat.kg/index.php?")
form2['Post'].value = 'up'
m.submit_form(form2)
I can sign in to the website so form1 works, but when I try in this case leave a comment(up), form2 does not work.I am keep getting either InvalidSubmit error either Bad Request error. Code of form1 and code of form2 seem to be the same, but one works and another does not. I am using python3.5 and robobrowser, and I am using Mac OS if that's gonna help. Thank you in advance.
Here is my traceback:
Traceback (most recent call last):
File "/Users/bkkadmin/Desktop/Daniiar/upper/test2.py", line 18, in <module>
m.submit_form(form)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/browser.py", line 339, in submit_form
payload = form.serialize(submit=submit)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/forms/form.py", line 226, in serialize
include_fields = prepare_fields(self.fields, self.submit_fields, submit)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/robobrowser-0.5.3-py3.5.egg/robobrowser/forms/form.py", line 154, in prepare_fields
raise exceptions.InvalidSubmitError()
robobrowser.exceptions.InvalidSubmitError
I experienced the same issue today, with the same exact errors. One possible cause of the above issue is that your form2 actually contains more than one submit field, corresponding to more than one submit button in the original html. You can check this by print(len(list(form2.submit_fields.items(multi=True)))). If this is the case, your call to submit_form has to be modified as m.submit_form(form2, submit=your_submit), where the second argument your_submit is the relevant submit field you want to use. This reference discusses how to extract the submit field you desire.
Incidentally, if you wonder where the long print code comes from, it comes from the body of prepare_fields in robobrowser/forms/form.py, which is indicated in one of the error outputs you posted.
Hope this helps!
It happens when the package you installed courrupted in your current project...
So try to create a new project in pycharm. And install robobrowser library again....
And paste your file in new project...
Noteuse this method only if your code is completely correct 😉