lovvskillz / python-discord-webhook Goto Github PK
View Code? Open in Web Editor NEWexecute discord webhooks
License: MIT License
execute discord webhooks
License: MIT License
like i want to put a text that when u click on it it bring to a site (in embed field)
Hello, when message contains too much character its cut , is this possible to split the message ?
status code 400: InvalidArgument
Invalid argument.
Hi, when my discord webhook gets rate limited, this module prints out the error message which I do not want to happen. Is there any way to stop it from printing out likes this? Also is there any other handling of rate limits that I don't know about? Thank you!!
While trying to pass a list of embeds to DiscordWebhook constructor, the execute method throws TypeError: Object of type 'DiscordEmbed' is not JSON serializable
.
Simple testing code:
from discord_webhook import DiscordWebhook, DiscordEmbed
if __name__ == "__main__":
embed = DiscordEmbed(title="Test embed")
webhook = DiscordWebhook(url="Valid Webhook URL", embeds=[embed])
webhook.execute()
I want to get the attachments inside of embed, tried both
but the attachment comes out of embed,
Code is as follows:
from discord_webhook import DiscordWebhook, DiscordEmbed
from start import config
import os
def send_message(msg, webhook):
webhook = DiscordWebhook(url=webhook)
embed = DiscordEmbed(description=msg, color='55FF06')
webhook.add_embed(embed)
response = webhook.execute()
def send_media(photoPath, webhook):
try:
with open(photoPath, "rb") as f:
filename = photoPath.split("\\")[-1]
webhook = DiscordWebhook(url=webhook)
webhook.add_file(file=f.read(), filename=filename)
embed = DiscordEmbed(color='55FF06')
embed.set_image(url='attachment://filename')
webhook.add_embed(embed)
response = webhook.execute(remove_files=True)
os.remove(photoPath)
except:
return
def send_media_caption(photoPath, photoCaption, webhook):
try:
with open(photoPath, "rb") as f:
filename = photoPath.split("\\")[-1]
webhook = DiscordWebhook(url=webhook)
webhook.add_file(file=f.read(), filename=filename)
embed = DiscordEmbed(description=photoCaption, color='55FF06')
embed.set_thumbnail(url='attachment://filename')
webhook.add_embed(embed)
response = webhook.execute(remove_files=True)
os.remove(photoPath)
except:
return
Hello.
I want to implement exception handling, but I don't know what kind of error will occur.
Are there any user defined exceptions?
How do i change the avatar of the webhook, passing in avatar kwarg
or avatar_url
doesn't work. How do I fix this?
Traceback (most recent call last):
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Senuka\Documents\fearless\cogs\mod.py", line 49, in hey
response = webhook.execute()
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\discord_webhook\webhook.py", line 119, in execute
response = requests.post(url, json=self.json, proxies=self.proxies, params={'wait':True})
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\api.py", line 119, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\sessions.py", line 528, in request
prep = self.prepare_request(req)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\sessions.py", line 456, in prepare_request
p.prepare(
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\models.py", line 319, in prepare
self.prepare_body(data, files, json)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\requests\models.py", line 469, in prepare_body
body = complexjson.dumps(json)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\__init__.py", line 395, in dumps
return _default_encoder.encode(obj)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\encoder.py", line 298, in encode
chunks = list(chunks)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\encoder.py", line 696, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\encoder.py", line 652, in _iterencode_dict
for chunk in chunks:
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\encoder.py", line 716, in _iterencode
o = _default(o)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\simplejson\encoder.py", line 272, in default
raise TypeError('Object of type %s is not JSON serializable' %
TypeError: Object of type Asset is not JSON serializable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\users\senuka\appdata\local\programs\python\python38-32\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Asset is not JSON serializable
I've created a simple-to-use, easy-to-follow CLI for using this tool to fully customize and send content to a user-definable webhook URL. It also supports the full capacity to save the webhookURL with AES Encryption. A link to download it can be found here, as well as usage instructions; try it out and let me know how it works. If you want, I can send in the source code and it can be added directly into the repo.
Features
Whenever I try to have the webhook execute I get the following error, and I can't seem to be able what causes it.
My code:
Help would be appreciated :)
Hey! Are you planning to add multiple webhooks support?
Weird issue where when posting to the webhook and displaying the timestamp in the embed the time is off by a few minutes. Is there somewhere we can have this run more frequently, maybe a for loop? I've seen it come as far off as 30-60 mins. I'm not sure I completely understand where you are calling for the time to be updated, but would appreciate any assistance. Using latest code.
In image, the time in the lower left is my system timestamp that is being run on my script at the time of execution, and the time in the embed is the after result from posting to Discord.
Currently have 3 servers and 2 of them doing double posting.
I tried transferring the script from another server because I thought its a server issue but still happening.
I can't replicate the issue because its random only but I can provide screenshots.
Hey,
I took a look at DiscordWebhook.json
property which is accessed in DiscordWebhook.execute
method.
When you call DiscordWebhook.execute()
method in your Python code there are still DiscordEmbeds in self.embeds
after the call because self.embeds
never gets emptied in the current code.
Example from the DiscordWebhook.json property:
self.embeds
are stored into embeds
variableself.embeds
is set to empty list
for
loop loops through embeds
variable and adds them to self.embeds
using self.add_embed
Outcome: future calls to execute()
using same instance will contain duplicate DiscordEmbed
instances.
Is this design choice or an oversight by the developer?
e.g. is it up to the user of this module to remove embeds using remove_embed
method after execute
is called to avoid this situation?
I left a comment to issue #1 (comment)
Here is example code which highlights the issue:
import time
from discord_webhook import DiscordWebhook, DiscordEmbed
discord_webhook = DiscordWebhook(url=['https://discord.com/api/webhooks/...........'])
for i in range(1, 10):
embed = DiscordEmbed(title=i, description='Test {}'.format(i))
discord_webhook.add_embed(embed)
discord_webhook.execute()
time.sleep(1)
discord-webhook version: 0.11.0
Hy, does someone know how i can change the logo webhook with the module ?
Ive been trying to get the information that disctord webhooks should return when rate limits are applied as seen in discord developer portal and I can't find a way to get the data using this module. Is there a way to get this data? If there is no way, are you pretending on updating this?
Edit:
It may be as easy as returning the response when calling webhook.execute()
Discord webhooks support an allowed_mentions
field, which sets the allowed mention types for the message. This is needed in some cases to prevent webhooks from tagging people/roles/@everyone
when they contain user-controlled data.
https://discord.com/developers/docs/resources/webhook#execute-webhook
https://discord.com/developers/docs/resources/channel#allowed-mentions-object
File "\Python\Python37\lib\site-packages\discord_webhook\webhook.py", line 139, in execute
self.sent_message_id = json.loads((responses[0] if len(responses) == 1 else responses).content.decode('utf-8'))['id']
AttributeError: 'list' object has no attribute 'content'
When I attempt to send more than 1 webhook. Please look into this, it was working a day or two ago... now it isnt and i havent changed any code
Hello guys!
Today I discovered that when I used one webhook, it sometimes returns as just one string etc if I do
response = webhook.execute()
print(response)
as:
<Response [200]>
but lately I did find out that it sometimes returns as:
[<Response [200]>]
I assume this is sort of bug where it shouldn't mix between list and non-list when sending only using one webhook
This cause me an error where I cant use response.ok anymore since its inside a List but that shouldn't happen if im not using multiple webhooks url which I dont.
Name: discord-webhook
Version: 0.11.0
Summary: execute discord webhooks
Home-page: https://github.com/lovvskillz/python-discord-webhook
Author: Vadim Zifra
Author-email: [email protected]
License: MIT License
Location: /home/barry/.local/lib/python3.8/site-packages
Requires: requests
Required-by:
Hi! I've been experimenting with this package, which is working awesomely. Only problem is, it deletes the embedded messages after a certain amount of time. Is there any way to stop it from doing that?
is there any way we could hide these errors?
[2020-01-07 07:20:24,609: ERROR/ForkPoolWorker-5] [0/1] Webhook status code 429: {
"global": false,
"message": "You are being rate limited.",
"retry_after": 1616
}
Hi,
Seems like:
b6d6eee#diff-fac559e83caf3a7ecc24b38e4a1db87022fa73c81a427a1e18f090216b85adbcR139
Broke the latest version of discord_webhook.
When sending messages to multiple webhooks using:
message = "Test123\n"
webhook = DiscordWebhook(url=['XXXX', 'XXXXX'], content=message)
webhook.execute()
Result:
File "/usr/local/lib/python3.8/site-packages/discord_webhook/webhook.py", line 139, in execute
self.sent_message_id = json.loads((responses[0] if len(responses) == 1 else responses).content.decode('utf-8'))['id']
AttributeError: 'list' object has no attribute 'content'
I'm posting the same embedded content to multiple (5 in total) different discord channels. Each DiscordWebhook is executed within the same function where the one DiscordEmbed is declared i.e.
webhook1.add_embed(embed)
webhook1.execute()
webhook2.add_embed(embed)
webhook2.execute()
...
were each webhook[x] is a separate DiscordWebhook and embed is a single reused DiscordEmbed.
The issue is that sometimes the embedded post appears multiple times in each specified channel. For now I'm having to remove the duplicates manually.
Any ideas on what could be causing the issue? I've had a look but nothing is sticking out at me.
If a webhook returns an error such as a 429 error, there should be a way to iterate through the supplied dict of proxies.
As far as I'm aware, setting the proxies for a webhook object does not persist through a While or For-loop if it is nested. As such, proxies (to my albeit mediocre coding skills) can't be changed per n messages sent.
The proxies used by the webhook should be an attribute of the webhook so debugging for proxy usage is easier.
I see no documentation for emoji support, is it possible to be added?
Hi, How to add Avatar/Profile Image for Webhook?
What is the format for the colour when using the embed libary?
Say I wanted to show the hex colour #ffa800 , how would I represent this in the formatting the libary requires?
Hi, is it possible to send a clickable hyperlink with custom text with this libary?
Thanks
Does anyone know how it could work when it exceeds the embed limit in a single message, worked a list and when the result is true, add an embed to the list. In some cases, from the list you could add more than 20 embed
I have same issue, but with files.
remove_embed removes only embed, but there is no alternative for attached files.
It would be nice to be able to change the image of the Bot that sends the messages, using the avatar_url
according to the Discord documentation.
raceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/models.py", line 379, in prepare_url
scheme, auth, host, port, path, query, fragment = parse_url(url)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/util/url.py", line 234, in parse_url
raise LocationParseError(url)
urllib3.exceptions.LocationParseError: Failed to parse: //<discord_webhook.webhook.DiscordWebhook object at 0x102b4ad90>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/dorianvoka/Desktop/telegram.py", line 29, in
response = webhook.execute()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord_webhook/webhook.py", line 144, in execute
response = requests.post(url, json=self.json, proxies=self.proxies, params={'wait': True}, timeout=self.timeout)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/api.py", line 116, in post
return request('post', url, data=data, json=json, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/sessions.py", line 519, in request
prep = self.prepare_request(req)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/sessions.py", line 452, in prepare_request
p.prepare(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/models.py", line 313, in prepare
self.prepare_url(url, params)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/models.py", line 381, in prepare_url
raise InvalidURL(*e.args)
requests.exceptions.InvalidURL: Failed to parse: //<discord_webhook.webhook.DiscordWebhook object at 0x102b4ad90>
I'm unable to match the colour to the type of webhook. Could you list the colour code along with the colour name>
Is it possible to embed youtube videos?
After inspection of the python-discord-webhook code base, I could not find any functionality that allowed for the webhook to be executed again if the user has received a status_code of 429 and is being rate limited by Discord. It seems like that any sort of retry based error handling is down to the user and there is currently no documentation on how to error handle being rate limited.
I have made my own implementation to handle being rate limited and retry to send the webhook again after a specific period of time (dependent on the webhook response sent after being rate limited), however, before I submit a pull request for this I would like to know if people would find this to be a useful feature to add to the package or would people rather just make their own implementation for handling this type of error.
Reinstalled python and I checked environment paths. Tried pip3 install, tried running script as python3, python, and py.
Dont know what to do anymore I also reinstalled the library.
I have been trying to print errors, without success. I used:
webhook = DiscordWebhook(url="URL")
embed = DiscordEmbed(title="Some text")
webhook.add_embed(embed)
try:
response = webhook.execute()
except Exception as error:
print(error)
I'd like to request asynchronized webhook generation, looping, and message sending since I am experiencing performance issues while the webhooks are synchronous.
Error log:
TypeError: object Response can't be used in 'await' expression
Ignoring exception in on_guild_channel_create
Traceback (most recent call last):
File "C:\Users\User\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:/Users/User/Desktop/Discord Shit/gen-bot/testwebhook.py", line 221, in on_guild_channel_create
await webhook.execute()
TypeError: object Response can't be used in 'await' expression
Ignoring exception in on_guild_channel_create
Traceback (most recent call last):
File "C:\Users\User\AppData\Roaming\Python\Python36\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:/Users/User/Desktop/Discord Shit/gen-bot/testwebhook.py", line 221, in on_guild_channel_create
await webhook.execute()
TypeError: object Response can't be used in 'await' expression
how to run it if i has one http proxy sever address?
webhook = DiscordWebhook(url=Webhook_URL, username=whn)
embed = DiscordEmbed(title=':tada: Footlocker In Store Raffle Confirmed! :tada:', color=65042)
embed.set_thumbnail(url=icon)
embed.set_author(name=whn)
embed.set_footer(text=f'| Alliance IO CLI | {Version} | FTL |', icon_url='https://static.wixstatic.com/media/7e8497_64f1127cd3b54ca1abf4155599062906~mv2.png/v1/fill/w_40,h_40,al_c,q_85,usm_0.66_1.00_0.01/Profile%20Picture.webp')
embed.set_timestamp()
embed.add_embed_field(name='Email ๐ง:', value="||"+email+"||",inline=False)
embed.add_embed_field(name='Size :', value=size)
embed.add_embed_field(name='Reservation ID:', value="||"+reservationid+"||",inline=False)
embed.add_embed_field(name='Shoe-ID ๐ท:', value=sku,inline=False)
embed.add_embed_field(name='Winning Store :', value=store1,inline=False)
embed.add_embed_field(name='Task Number:', value=TA,inline=False)
embed.set_image(url='path to file')
webhook.add_embed(embed)
try:
response = webhook.execute()
except Exception as ex:
print('Webhook Failure, Raffle Has Been Entered!')
When trying to send a local picture (png) im returned with the status code 400.
The webhook stops transmitting data to Discord after a while. It happened thrice now, the first one happened after the script has been running for 12 hours, the second one the script is running for 9 hrs, and now after 7 hrs.
The output is just stuck to:
Uploaded: [ last data in discord ]
And the data at discord channel shows: last data in discord
.
No exceptions have been triggered.
I have the excerpt of the script, more info can be found on my gitlab with the project entitled: chat-uploader-discord-webhook
. Beware it's not pretty and doesn't follow PEP8.
# tail a log file
# sleep_time is default to 1
# chat_message is the one being fetched from a log file
# VERBOSE is set to True
time.sleep(sleep_time)
webhook = DiscordWebhook(url=webhookurl, content=chat_message)
webhook_execute = webhook.execute()
# Credits: https://github.com/novasz @ https://github.com/lovvskillz/python-discord-webhook/issues/47
# Check if webhook response is 200/204
if webhook_execute.status_code in [200, 204]:
if VERBOSE:
print("Uploaded: [" + chat_message + "]\n")
# We are being rate limited :(
if webhook_execute.status_code == 429:
errors = json.loads(webhook_execute.content.decode('utf-8'))
wh_sleep = (int(errors['retry_after']) / 1000) + 0.15
print("Webhook rate limited: sleeping for " + str(wh_sleep) + " seconds...")
# Sleep
time.sleep(wh_sleep)
# Upload rate limit hit message, discard other messages
webhook = DiscordWebhook(url=webhookurl, content=rate_limit_message)
webhook_execute = webhook.execute()
if webhook_execute.status_code in [200, 204]:
if VERBOSE:
print("Notify Ratelimit was hit\n")
# hmm add if 429 here?
I will update the script later, or maybe just add another script that will terminate the python script after a set time interval and restart it.
Please confirm whether others can reproduce this problem or its just my code problem. Thanks.
I receive this error when sending a webhook to multiple webhook urls
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 731, in get_adapter raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for '['https://discordapp.com/api/xxx', 'https://discordapp.com/api/webhooks/xxx']'
My code
def send_webhook(link, quantiy, info, webhook): webhook_links = ['https://discordapp.com/api/webhooks/xxx, 'https://discordapp.com/api/webhooks/xxx'] webhook = DiscordWebhook(url=webhook) embed = DiscordEmbed(title = info[1] ,color = 242424, url=link, description='${} - Quantiy Available {}'.format(info[2], quantiy)) embed.set_thumbnail(url = info[0]) webhook.add_embed(embed) webhook.execute()
i used it how its supposed to be used and it just does not work
Here I have some code that should be setting the hook's name using the keyword arguments, but for some reason the name remains unchanged.
Python Version: 3.6.9
and tested on 3.8.0
Discord Webhook version: discord-webhook==0.8.0
(from pypi)
def post_to_webhook(self, gist_url, report_time):
logging.info("Posting the gist to the webhook...")
# Make a new webhook
webhook = DiscordWebhook(url=self.webhook_url, name=self.server)
# Create and embed and set time stamp for the embed, add it to the webhook and execute it.
embed = DiscordEmbed(title="{} crashed!".format(self.server), description="Read the report here: {}".format(gist_url))
embed.set_timestamp(report_time)
webhook.add_embed(embed)
return webhook.execute()
And as you can see below, the embed has self.server
filled appropriately, but the webhook's name does not change.
How can you add a hyperlink in the title of an embed?
Thank you
I tried to send message with embed field to my discord channel through webhook. Types of startSellDate, publicType and skusList are all 'str'. After execute(), it returns code 400 error.
discord-webhook version is 0.6.0.
def discordEmbedMessage(sneakerInfo, startSellDate, publicType, imageURL, skusList):
# descirption = "test"
# create embed object for webhook
embed = DiscordEmbed(title=sneakerInfo, description="ๅ็ฐๆฐๆฌพ", color=242424)
embed.add_embed_field(name='Sell Date', value=startSellDate, inline=False)
embed.add_embed_field(name='Public Type', value=publicType, inline=False)
embed.add_embed_field(name='SkusList', value=skusList, inline=False)
# set image
embed.set_image(url=imageURL)
# set footer
embed.set_footer(text='Coldplay')
# add embed object to webhook
webhook.add_embed(embed)
response = webhook.execute()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.