Содержание
- Ошибка при загрузке изображения с библиотекой запросов
- Ошибка разбора BadArgument и JSON при вызове API
- discord.ext.commands.errors.BadArgument: Expected space after closing quotation #1865
- Comments
- Name already in use
- api / docs_eng / errors.md
Ошибка при загрузке изображения с библиотекой запросов
Я пытаюсь внедрить OCR-переводчик Яндекса в свой код. С помощью Burp Suite мне удалось обнаружить, что для отправки изображения используется следующий запрос:
Я пытаюсь эмулировать этот запрос с помощью следующего кода:
хотя, к сожалению, это дает следующий результат:
Кто-нибудь знает, как это можно решить?
Я бы не стал воспроизвести границу для многостраничной загрузки даже здесь. Я, конечно, не стал бы воспроизводить каждый заголовок.
@MartijnPieters Большое спасибо за быстрый ответ. как бы вы воспроизвели его тогда?
Вы передаете результат MultipartEncoder.to_string() параметру files . Теперь вы запрашиваете запросы на кодирование результата составного кодировщика в составной компонент. Это на один раз слишком много.
Вам не нужно реплицировать здесь каждый байт, просто опубликуйте файл, а возможно установите пользовательский агент, реферер и источник:
Заголовок Связь лучше всего оставить для запросов, он может контролировать, когда соединение должно оставаться активным. Заголовки Принимать* предназначены для того, чтобы сообщать серверу, что может обрабатывать ваш клиент, и requests также устанавливает их автоматически.
Я получаю ответ 200 OK с этим кодом:
Однако, если вы не устанавливаете дополнительные заголовки (убираете аргумент headers=headers ), запрос также работает, поэтому Яндекс здесь не фильтрует роботов.
Источник
Ошибка разбора BadArgument и JSON при вызове API
Внутри моего компонента я пытаюсь выполнить вызов api с помощью fetch.
API принимает путь к файлу образа .jpg как таковой — file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/F3B8EBCC-BB09-4603-AF7E-FD3CA792C237.jpg и должен возвращать объект JSON .
Вот мой вызов загрузки ниже:
Когда я запускаю приведенный выше код, он возвращает ошибку:
Есть мысли по этому поводу?
чтобы сделать тело сообщения правильным json-объектом.
Спасибо. это сработало. но теперь у меня другая проблема: файл фотографии, созданный камерой expo, возвращает ошибку. Object < «error»: Object < «code»: «InvalidURL», «message»: «Invalid image URL.», >, выставочная камера создает это: «uri»: «file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/E67E8249-2B53-49EA-B51D-42CD98768634.jpg» , но он возвращает ошибку, но любой адрес изображения из большинства изображений будет работать нормально.
Я думаю, вы найдете изображения, которые работают с сетевыми URL-адресами, такими как https: // . но URL-адреса file: /// не будут работать . у azure нет возможности загружать файлы локально на вашем компьютере. Вам нужно будет разместить свои изображения в том месте, где вы сможете использовать их с http: // url. Я не смотрел на API, но, возможно, есть способ встроить изображение как часть полезной нагрузки, а не просто URL-адрес.
Источник
discord.ext.commands.errors.BadArgument: Expected space after closing quotation #1865
It even seems to happen with the default help command
Very weird this is happening
The default help command accepts input, so that is expected behavior.
If your subscribe command also expects input arguments, unlike the one in your original issue description, then that is expected behavior as well.
It is expected behavior
I see the subscribe foo bar func in example above misses the args, my mistake
But why it raises a BadArgument on «»» + . It should be handled as a string.
It is expected behavior that an input argument of «»» will raise BadArgument because quotation marks are used to enter input with spaces, and like the error says, a space is expected after the closing quotation mark to signify the end of the argument.
See https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#parameters
I’m not sure how else you expect that input to be parsed.
To use a quotation mark inside a string, you can simply escape it:
# to embed a quote inside the string you must escape it: «a »world»»
For future questions like this, you should join either the official discord.py server or the Discord API server for help, as the README recommends.
It is expected behavior that an input argument of «»» will raise BadArgument because quotation marks are used to enter input with spaces, and like the error says, a space is expected after the closing quotation mark to signify the end of the argument.
In this case it should not matter since the input of a user gets unpacked. (basically what you showed in the doc link), Its very weird behavior that this exception also get raised from the default help function. I would’ve sworn that the default help function accepts *args.
To use a quotation mark inside a string, you can simply escape it:
to embed a quote inside the string you must escape it: «a «world»»
Besides I’m not looking to escape quotes, I can’t edit a users message before it enters the startpoint of the api. It won’t even enter my on_message function which is odd.
This is not a question but something wrong in the api. To verify this i have made a snippet of my actual code which you could inspect. It’s easy to draw quick conclusions.
Once more the error >
Just a reminder that I have no interests in escaping characters in any embed whats however.
The user input should correctly be handled as a String type which the backend magic does,
«»» + should be str(‘»»» +’) . Oh and one more thing If this was normal behavior other people in this thread would experience the same error on any func call with the args «»» + which they don’t. So no, its not normal behavior.
In this case it should not matter since the input of a user gets unpacked. (basically what you showed in the doc link)
The second quotation mark is not escaped, so when the input is parsed, the argument is taken to be an empty string with the first two quotation marks. The third quotation mark raises the BadArgument error as the parser does not expect anything after the second quotation mark besides a space, as that should be the end of the input for that argument.
Its very weird behavior that this exception also get raised from the default help function. I would’ve sworn that the default help function accepts *args.
The default help command accepts a variable number of parameters.
As the documentation notes, this has the same multi-word argument parsing for quotation marks as positional parameters.
Besides I’m not looking to escape quotes, I can’t edit a users message before it enters the startpoint of the api.
This has nothing to do with changing a user’s message.
The expected behavior for that input is to raise BadArgument because the parser doesn’t know how to interpret it. This is caused by an error in user input, the same way BadArgument is raised when a user enters something invalid for a channel, user, role, etc. input conversion.
It won’t even enter my on_message function which is odd.
This is not true. The error is raised when the command is invoked, which happens when you process the command in on_message .
This is not a question but something wrong in the api.
I already told you this is expected behavior, and I thought you agreed, since you said:
Hence why I referred you to the Discord servers, as I thought you were continuing with questions.
Regardless, this is not an issue with the library.
Just a reminder that I have no interests in escaping characters in any embed whats however.
Escaping quotation marks in input for multi-word arguments has nothing to do with embeds.
The user input should correctly be handled as a String type which the backend magic does,
«»» + should be str(‘»»» +’) .
I already explained why this doesn’t make sense and isn’t the case for positional and variable parameters.
As for keyword-only arguments, like in this subscribe command, that is the expected behavior and is what happens. I’m unable to reproduce the issue with a command with only a keyword-only argument parameter. game is successfully set to ‘»»» +’ .
Also, as previously noted, the latest version of the rewrite branch is currently v1.0.0a1650+g1222bce, not v1.0.0a11+gbe28250. The commit be28250 also does not exist in the repository.
Oh and one more thing If this was normal behavior other people in this thread would experience the same error on any func call with the args «»» + which they don’t.
I’m not sure what you mean. @LewdNeko likely didn’t encounter a BadArgument error like I didn’t, simply because your initial issue description was for a command with no input arguments. Like I’ve explained, «»» is only an invalid input for positional and variable parameters, so those are the only cases for which it’ll raise BadArgument . As far as I’m aware, no one else who has commented on this issue has said this is not the case. Otherwise, I’m not sure why «»» + would be common input at all or what it would even mean.
Источник
Name already in use
api / docs_eng / errors.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
Copy raw contents
Copy raw contents
Errors and response codes
API extensively uses informing through HTTP response codes. The application must process them correctly.
When an error occurs, the response body, besides the response code, will have an additional information that helps the developer to learn the cause of the error.
All errors are displayed in the format:
Several errors can be returned at the same time. The type key is present in each errors array object and contains a text identifier of the error class. The value key is optional and provides more detail on the error.
Apart from the errors described above, API can optionally return other keys left for backward compatibility. It is not recommended to use them.
If the requested resource can’t be found, the 404 Not Found response will be returned and the errors array will have the object:
If there is an error in request parameters (e.g. GET https://api.hh.ru/vacancies/?employer_id=foo ) the 400 Bad Request response will be returned, and the error array will have the object:
If the service can’t process the request at the moment, but understood it correctly, the 503 Service Unavailable response will be returned and type will contain service_unavailable .
In case of unforeseen situation, API will return 500.
In rare cases errors with 5** codes can be returned with the body that doesn’t contain the valid json. In such a case the application should rely only on the response code.
General request errors
HTTP code | type | value | description |
---|---|---|---|
400 | bad_user_agent | unset | User-Agent title is not transferred |
400 | bad_user_agent | blacklisted | User-Agent value in the black list |
Description of errors while receiving/updating tokens
Description of the fields:
Name | Type | Value |
---|---|---|
error | string | One of the values described in RFC 6749. For example, invalid_request if any of the required parameters were not transferred |
error_description | string | Additional description of the error |
Below are some of the possible errors with descriptions.
HTTP code | error | error_description | описание |
---|---|---|---|
400 | invalid_request | account not found | This error can occur if an invalid client_id and client_secret pair was transferred |
account is locked | User account is locked. The user must contact the website support team | ||
password invalidated | User account password is outdated. The user must restore the password on the website https://hh.ru | ||
login not verified | User account is not verified. The user must contact the website support team | ||
bad redirect url | Invalid redirect_url was transferred | ||
token is empty | refresh_token was not transferred | ||
token not found | Invalid refresh_token was transferred | ||
code not found | The transferred authorization_code was not found | ||
400 | invalid_client | client_id or client_secret not found | The error can occur if this client_id was not found or has been deleted, or if an invalid client_secret was transferred |
400 | invalid_grant | token has already been refreshed | The error occurs when trying to re-use the refresh token |
token not expired | The error occurs when trying to update a valid access token. access token can be updated only after expiration | ||
token was revoked | The token was revoked. For example, a token is revoked if the password has expired | ||
bad token | An invalid token value was transferred | ||
code has already been used | authorization_code has already been used (it can only be used once) | ||
code expired | authorization_code expired | ||
code was revoke | authorization_code was revoked (if the password has expired) | ||
token deactivated | The token was deactivated. The token is deactivated if the user has changed the password | ||
400 | unsupported_grant_type | unsupported grant_type | The error occurs if an invalid value in the grant_type field was transferred |
403 | forbidden | app token refresh too early | The error occurs if the application token is requested more than once every five minutes |
Authorization use errors
In case you make an authorized request in api and your authorization is not valid for any reason, an error with type oauth , and, possibly, with one of the listed values , will be returned.
HTTP code | type | value | description |
---|---|---|---|
403 | oauth | bad_authorization | authorization token doesn’t exist or is not valid |
403 | oauth | token_expired | access_token validity period has expired, it is necessary to refresh the access_token authorization.md#refresh_token |
403 | oauth | token_revoked | the token is revoked by the user, the application should request a new authorization |
403 | oauth | application_not_found | your application has been deleted |
Errors when accessing a paid method
In case you request a paid method without buying access, the following error will be generated:
HTTP code | type | value | description |
---|---|---|---|
403 | api_access_payment | action_must_be_payed | You have requested a paid method without buying access |
Errors of separate resources
If the service can return more detailed information on the error, it will be given in the response body. In this case the response code will likely be 400, 403, 409, 429, but other codes are also possible.
At the least, the application should process HTTP response statuses correctly. To facilitate the work with the application, it is recommended to also process the response type that has come. The tables listed below contain an incomplete error list; it can be extended.
Saved resume searches
In addition to the error code pertaining to the transfer of a saved resume search to another manager, the following errors may return:
HTTP code | type | value | description |
---|---|---|---|
404 | saved_searches | saved_search_not_found | auto search not found or not owned by current user |
404 | saved_searches | manager_not_found | invalid manager_id |
When uploading artifacts, errors are possible, including:
HTTP code | type | value | description |
---|---|---|---|
400 | bad_argument | file | file not specified, or several files specified |
400 | bad_argument | type | incorrect parameter type value |
400 | bad_argument | description | description too long |
400 | artifacts | limit_exceeded | number of artifacts exceeded |
400 | artifacts | image_too_large | file size exceeds the limit |
400 | artifacts | unknown_format | unknown file format |
403 | forbidden | — | insufficient access rights |
In addition to general errors, the following errors may be returned:
HTTP code | type | value | description |
---|---|---|---|
403 | negotiations | invalid_vacancy | the vacancy from the response/invitation was archived or hidden |
400 / 403 | negotiations | resume_not_found | the CV from the response/invitation was hidden or deleted, or not found |
400 / 403 | negotiations | limit_exceeded | the limit on the responses/invitations number was exceeded |
403 | negotiations | wrong_state | the action on the response/invitation in this status is impossible |
403 | negotiations | empty_message | the empty message text was sent |
403 | negotiations | too_long_message | the too long message text was sent |
403 | negotiations | address_not_found | the address sent for the action does not exist or belongs to another employer |
403 | negotiations | not_enough_purchased_services | the required paid services are not available, this usually refers to access to the resume database |
403 | negotiations | not_enough_purchased_services | the paid services are insufficient, usually CV database service |
403 | negotiations | in_a_row_limit | the number of successive messages is exceeded; the opponent must reply to the message in order the employer is able to send new messages |
403 | negotiations | overall_limit | messages limit exceeded |
403 | negotiations | no_invitation | negotiations are unavailable as there was no invitation in the response |
403 | negotiations | message_cannot_be_empty | negotiation message cannot be empty |
403 | negotiations | disabled_by_employer | negotiation by response is disabled by the employer |
403 | negotiations | resume_deleted | the message can’t be sent as the CV referenced in the response is deleted or hidden |
403 | negotiations | archived | the message can’t be sent as the vacancy referenced in the response is archived |
403 | negotiations | chat_archived | action regarding a response/invitation can’t be performed as response/invitation is archived |
When adding to the list of selected vacancies the following errors can be returned, in addition to the error code:
HTTP code | type | value | description |
---|---|---|---|
403 | vacancies_favorited | vacancy_archived | the vacancy is archived and cannot be added to the list of selected number of selected vacancies exceeds the limit |
403 | vacancies_favorited | limit_exceeded | authorization_code has already been used (it can only be used once) |
Vacancy posting and editing
In addition to an error code, the following errors may be returned when posting and editing a vacancy:
HTTP code | type | value | description |
---|---|---|---|
400 | vacancies | field_name | the is an error in a job’s field, where the field_name is the key of the upper level field and the reason field may be missing |
403 | vacancies | not_enough_purchased_services | the purchased services are not enough to publish or update this type of job |
403 | vacancies | quota_exceeded | the manager’s quota for the publication of this type of job is exhausted |
403 | vacancies | duplicate | a similar job has already been published; the response contains information about duplicate jobs; this error can be disabled by force (when adding or editing) |
403 | vacancies | creation_forbidden | jobs cannot be published by the current manager |
403 | vacancies | unavailable_for_archived | you cannot edit an archived job |
403 | vacancies | conflict_changes | a conflict was detected between changes to the job’s data (read more) |
Reasons for errors
reason | description |
---|---|
is_empty | empty value |
wrong_size | wrong value size |
is_too_short | value size is too small |
is_too_long | value size is too big |
currency_code_is_invalid | the salary currency is incorrect |
chosen_area_is_not_a_leaf_or_not_exist | the vacancy location is incorrect or is not the final region (city, town) |
email_in_description | the vacancy description contains an email |
anonymous_vacancy_contains_address | an anonymous vacancy should not contain the employer’s address |
anonymous_vacancy_has_real_company_name | the vacancy title should not contain the employer’s company name |
only_for_anonymous_type | this action is only available for anonymous vacancies |
address_is_disabled | address is unavailable |
vacancy_type_employer_billing_type_mismatch | the vacancy type is incompatible with current billing type |
only_for_direct_type | this action is only available for direct vacancies |
address_is_empty_with_checked_show_metro_flag | empty address was entered together with an indication to show the metro station |
address_has_no_metro_but_checked_show_metro_flag | a metro station is not available at the entered address, but the option to show the metro station is selected |
default_vacancy_branded_template_is_invalid_or_not_enough_purchased_services | branded vacancy template is entered incorrectly, or you have not paid for the service allowing you to use a branded vacancy template |
department_code_prohibited_in_anonymous_vacancy | you cannot specify a department code for an anonymous vacancy |
branded_template_prohibited_in_anonymous_vacancy | you cannot use a branded template for an anonymous vacancy |
value_conflict_with_business_rules | you cannot use specified billing_type |
Example response on error duplicate
Path | JSON type | Description |
---|---|---|
found | number | total number of duplicate jobs |
items | array | limited number of records with information about duplicates. Does not guarantee all duplicates will be returned. |
items[].id | number | job id |
In addition to the error code, the following errors can be returned when extending a job:
HTTP code | type | value | description |
---|---|---|---|
403 | vacancies | not_enough_purchased_services | the purchased services are insufficient for prolongation of this type of vacancy |
403 | vacancies | quota_exceeded | the manager’s quota for posting of this type of vacancies has been exceeded |
403 | vacancies | prolongation_forbidden | extension of vacancies is unavailable for the current manager |
403 | vacancies | unavailable_for_archived | extension of vacancies is unavailable for the archived vacancy |
403 | vacancies | too_early | premature extension |
In addition to general errors, the following errors can be returned when editing an employer’s manager:
HTTP code | type | value | reason | description |
---|---|---|---|---|
400 | managers | field_name | error in the field_name field | |
403 | managers | already_exist | a manager with this email address already exists | |
403 | managers | creation_limit_exceeded | the limit for creating managers has been reached | |
403 | managers | field_name | not_editable | the field_name field cannot be edited |
Working with a resume
In addition to general errors, the following errors can be returned when getting or updating a resume:
HTTP code | type | value | description |
---|---|---|---|
400 | bad_argument | with_contact | incorrect field value with_contact |
400 | resumes | total_limit_exceeded | the allowed number of resumes is exceeded (this applies only to applicants) |
429 | resumes | view_limit_exceeded | the allowed number of resume views is exceeded (this applies only to employers) |
403 | resumes | quota_exceeded | resume viewing quota available to manager has been exceeded (applies to employers only) |
403 | resumes | no_available_service | no sufficient services available to view resume |
403 | resumes | cant_view_contacts | no contact viewing rights |
In addition to the type and value , the returned error response body may contain a description , i.e., description of the events that give rise to the error in question.
Adding hidden jobs to the list
In addition to general errors, the following errors can be returned when adding hidden jobs to the list:
HTTP code | type | value | description |
---|---|---|---|
400 | vacancies_blacklist | limit_exceeded | the allowed number of hidden jobs is exceeded |
404 | vacancies_blacklist | not_found | the job to be added to the list has not been not found |
Adding hidden companies to the list
In addition to general errors, the following errors can be returned when adding company’s hidden jobs to the list:
HTTP code | type | value | description |
---|---|---|---|
400 | employers_blacklist | limit_exceeded | the allowed number of hidden jobs is exceeded |
404 | employers_blacklist | not_found | the job to be added to the list has not been not found |
Resume visibility lists
Getting visibility lists
HTTP code | type | value | description |
---|---|---|---|
400 | bad_argument | per_page | an invalid number of items per page was passed (the maximum value is 100) |
Adding companies to the list
HTTP code | type | value | description |
---|---|---|---|
400 | resume_visibility_list | unknown_employer | an unknown employer ID was passed |
400 | resume_visibility_list | limit_exceeded | visibility list limit exceeded |
400 | resume_visibility_list | too_many_employers | too many employers were passed |
Removing companies from the list
HTTP code | type | value | описание |
---|---|---|---|
400 | bad_argument | id | an invalid employer ID was passed |
400 | resume_visibility_list | too_many_employers | too many employers were passed |
HTTP code | type | value | reason | описание |
---|---|---|---|---|
400 | bad_argument | id | too_many_bulk_items | too many IDs |
400 | bad_argument | id | an invalid ID was passed |
Manager work accounts
HTTP code | type | value | description |
---|---|---|---|
403 | manager_extra_accounts | manager_extra_account_not_found | Incorrect Account ID in the header |
403 | manager_accounts | used_manager_account_forbidden | Work Account is blocked |
If User Account is blocked, the following error message will be generated:
where allowed_accounts contains an array of the accounts available for this token Array elements are similar to the result in the list of the Work Accounts
The captcha requirement
Some operations in API may be protected with a captcha. It is clearly indicated in the resource description where the captcha test applies. The following error is returned in this case :
Name | Type | Description |
---|---|---|
fallback_url | string or null | Address of the webpage where a similar operation can be completed (more often than not, the page itself is protected with a captcha) |
captcha_url | string or null | Address of the webpage where to pass the captcha. Once the captcha is passed successfully, a similar request in API should also be completed successfully. The app is to add to captcha_url the required parameter backurl , to which the redirect will go after the captcha is passed. The backurl must always contain a schema, e.g., https:// , or the app schema |
One or the other of the fallback_url or captcha_url parameters may be absent, but both cannot be absent at the same time.
- 403 Forbidden — captcha required (this will never come, unless the token has not been transmitted)
Источник
I have a problem while using the sample view «Biblio OAI-PMH» in an HTTP GET request :
Have you an explanation ?
Thanks in advance
Comments
Unfortunately I can’t explain that, it should work. I just tried the same URL on my system and it works as expected.
You might try clearing your «views» cache (admin/structure/views/settings/advanced) to see that helps.
- Log in or register to post comments
Thank you for your answer.
Unfortunately, the clearing of the views-cache doesn’t resolve the problem.
What is the component’s version which is working on your system ?
- Log in or register to post comments
You do need Views 3.x to use this plugin, (probably the latest -dev of both views and ctools is a good idea).
- Log in or register to post comments
Here are my versions :
Views 7.x-3.x-dev
Views OAI-PMH 7.x-1.0-beta1
Chaos tools 7.x-1.x-dev
Do you think that’s OK ?
- Log in or register to post comments
Yep, (assuming those -devs are the latest) it looks all good.
What happens if you enter the following…
/oai?verb=ListRecords&metadataPrefix=oai_dc
- Log in or register to post comments
With /oai?verb=ListRecords&metadataPrefix=oai_dc :
Do not use them same argument more than once.
The combination of the given values results in an empty list.
- Log in or register to post comments
Did you change the «path» in the view?
You might try un-installing and re-installing the module.
- Log in or register to post comments
1 : no, I keep the default value for the path : Path: /oai
2 : if I re-install the module, what is your recommendation : do I take the version 7.x-1.0-beta1 or 7.x-1.x-dev ?
- Log in or register to post comments
I don’t think there have been any changes to the -dev version since beta1 so they are essentially identical.
- Log in or register to post comments
Here is what I did :
— update ctools (rc1)
— uninstall module «Views OAI-PMH»
— reinstall v. 7.x-1.x-dev
— clear views’ cache + all caches
— test of /oai?verb=ListRecords&metadataPrefix=oai_dc
— always the same error page :
«Do not use them same argument more than once.»
«The combination of the given values results in an empty list.»
In the file views_oai_pmh_plugin_display.inc, it seems to be the error code ‘sameArgument’ (in function oai_error) ??
- Log in or register to post comments
OK, maybe we need to go outside the module to more detail about your setup.
What OS/Web server/PHP versions are you using?
- Log in or register to post comments
I tried :
— Wampserver 2.0 on windows 7 SP1 — AND — apache 2 on debian 6.0
— Both with PHP 5.3.0 and Drupal 7.2
- Log in or register to post comments
I think the issue is related to the content (or lack there of) of the $_SERVER global.
Try commenting out lines 207 — 210 in views_oai_pmh_plugin_display.inc as shown below…
function parse_oai_request(){
$args = array();
if (!empty($_GET)) {
$args = $_GET;
// $getarr = explode('&', $_SERVER['QUERY_STRING']);
// if (count($getarr) != count($args)) {
// $this->oai_error('sameArgument');
// }
}
if (!empty($_POST)) {
$args = $_POST;
}
- Log in or register to post comments
OK, thank you very much : it works !
In your mind, what’s the best solution :
— let these lines commented
— put a content on $_SERVER : have you an example ?
- Log in or register to post comments
Now that you have confirmed that this is the problem, I’m going to remove those lines from the code since they were carried forward from some older code and I don’t think they are really necessary in the context of this module.
Cheers,
Ron.
- Log in or register to post comments
Status: | Active | » Closed (fixed) |
I hope this will be useful for other users of your very important module.
Many thanks again.
Bye
- Log in or register to post comments
- Log in or register to post comments
You are passing the MultipartEncoder.to_string()
result to the files
parameter. You are now asking requests to encode the result of the multipart encoder to a multipart component. That’s one time too many.
You don’t need to replicate every byte here, just post the file, and perhaps set the user agent, referer, and origin:
files = {
'file': ("blob", open("image_path", 'rb'), "image/jpeg")
}
url = "https://translate.yandex.net:443/ocr/v1.1/recognize?srv=tr-image&sid=9b58493f.5c781bd4.7215c0a0&lang=en%2Cru"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0",
"Referer": "https://translate.yandex.com/",
"Origin": "https://translate.yandex.com",
}
response = requests.post(url, headers=headers, files=files)
print(response.status)
print(response.json())
The Connection header is best left to requests, it can control when a connection should be kept alive just fine. The Accept* headers are there to tell the server what your client can handle, and requests
sets those automatically too.
I get a 200 OK response with that code:
200
{'data': {'blocks': []}, 'status': 'success'}
However, if you don’t set additional headers (remove the headers=headers
argument), the request also works, so Yandex doesn’t appear to be filtering for robots here.
Вы передаете результат MultipartEncoder.to_string() параметру files. Теперь вы запрашиваете запросы на кодирование результата составного кодировщика в составной компонент. Это на один раз слишком много.
Вам не нужно реплицировать здесь каждый байт, просто опубликуйте файл, а возможно установите пользовательский агент, реферер и источник:
files = {
'file': ("blob", open("image_path", 'rb'), "image/jpeg")
}
url = "https://translate.yandex.net:443/ocr/v1.1/recognize?srv=tr-image&sid=9b58493f.5c781bd4.7215c0a0&lang=en%2Cru"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0",
"Referer": "https://translate.yandex.com/",
"Origin": "https://translate.yandex.com",
}
response = requests.post(url, headers=headers, files=files)
print(response.status)
print(response.json())
Заголовок Связь лучше всего оставить для запросов, он может контролировать, когда соединение должно оставаться активным. Заголовки Принимать* предназначены для того, чтобы сообщать серверу, что может обрабатывать ваш клиент, и requests также устанавливает их автоматически.
Я получаю ответ 200 OK с этим кодом:
200
{'data': {'blocks': []}, 'status': 'success'}
Однако, если вы не устанавливаете дополнительные заголовки (убираете аргумент headers=headers), запрос также работает, поэтому Яндекс здесь не фильтрует роботов.
Я пытаюсь внедрить в свой код переводчик Yandex OCR. С помощью Burp Suite мне удалось обнаружить, что для отправки изображения используется следующий запрос:
Я пытаюсь эмулировать этот запрос с помощью следующего кода:
import requests
from requests_toolbelt import MultipartEncoder
files={
'file':("blob",open("image_path", 'rb'),"image/jpeg")
}
#(<filename>, <file object>, <content type>, <per-part headers>)
burp0_url = "https://translate.yandex.net:443/ocr/v1.1/recognize?srv=tr-image&sid=9b58493f.5c781bd4.7215c0a0&lang=en%2Cru"
m = MultipartEncoder(files, boundary='-----------------------------7652580604126525371226493196')
burp0_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0", "Accept": "*/*", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Referer": "https://translate.yandex.com/", "Content-Type": "multipart/form-data; boundary=-----------------------------7652580604126525371226493196", "Origin": "https://translate.yandex.com", "DNT": "1", "Connection": "close"}
print(requests.post(burp0_url, headers=burp0_headers, files=m.to_string()).text)
Хотя, к сожалению, это дает следующий вывод:
{"error":"BadArgument","description":"Bad argument: file"}
Кто-нибудь знает, как это можно решить?
Спасибо заранее!
1 ответ
Лучший ответ
Вы передаете результат MultipartEncoder.to_string()
параметру files
. Теперь вы запрашиваете запросы на кодирование результата многокомпонентного кодера в многокомпонентный компонент. Это один раз слишком много.
Вам не нужно реплицировать каждый байт здесь, просто опубликуйте файл и возможно установите агент пользователя, реферер и источник:
files = {
'file': ("blob", open("image_path", 'rb'), "image/jpeg")
}
url = "https://translate.yandex.net:443/ocr/v1.1/recognize?srv=tr-image&sid=9b58493f.5c781bd4.7215c0a0&lang=en%2Cru"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0",
"Referer": "https://translate.yandex.com/",
"Origin": "https://translate.yandex.com",
}
response = requests.post(url, headers=headers, files=files)
print(response.status)
print(response.json())
Заголовок Connection лучше оставить для запросов, он может контролировать, когда соединение должно поддерживаться в рабочем состоянии. Заголовки Accept * предназначены для того, чтобы сообщить серверу, что может обработать ваш клиент, и requests
также устанавливает их автоматически.
Я получаю 200 OK ответ с этим кодом:
200
{'data': {'blocks': []}, 'status': 'success'}
Однако если вы не установите дополнительные заголовки (удалите аргумент headers=headers
), запрос также сработает, поэтому, похоже, Яндекс здесь не фильтрует роботов.
2
Martijn Pieters
28 Фев 2019 в 23:54
Внутри моего компонента я пытаюсь сделать api-вызов, используя fetch.
API принимает образ .jpg
путь к файлу как таковой — file:///var/mobile/Containers/Data/Application/1E1E919E-6C21-4CC7-B9C2-5B4B3BC84B0F/Library/Caches/ExponentExperienceData/%2540chuks93%252Fihu-main/Camera/F3B8EBCC-BB09-4603-AF7E-FD3CA792C237.jpg
и он должен вернуть объект JSON
.
Здесь мой запрос на выбор ниже:
export default {
processImage: (image) => {
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "*******************";var uriBase = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
// Display the image.
var sourceImageUrl = image;
console.log(typeof sourceImageUrl)
console.log("here", sourceImageUrl);// Perform the REST API call.
return fetch(uriBase, {method: 'POST',
headers: {
"Content-type": "application/json",
"Ocp-Apim-Subscription-Key": subscriptionKey
},body: JSON.stringify(sourceImageUrl),
})
.then((data) => data.json())
.then(function (data){
console.log("hello", data);
}).catch(function (error) {
console.log(error);
});
}
}
Когда я запускаю вышеуказанный код, это ошибка, которую он возвращает:
Object { "error": Object { "code": "BadArgument", "message": "JSON parsing error.", }
Любые мысли по этому поводу?
The following are 30
code examples of discord.ext.commands.BadArgument().
You can vote up the ones you like or vote down the ones you don’t like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
discord.ext.commands
, or try the search function
.
Example #1
def retrieve_emoji(self) -> typing.Tuple[str, str]: sent_emoji = self.config["sent_emoji"] blocked_emoji = self.config["blocked_emoji"] if sent_emoji != "disable": try: sent_emoji = await self.convert_emoji(sent_emoji) except commands.BadArgument: logger.warning("Removed sent emoji (%s).", sent_emoji) sent_emoji = self.config.remove("sent_emoji") await self.config.update() if blocked_emoji != "disable": try: blocked_emoji = await self.convert_emoji(blocked_emoji) except commands.BadArgument: logger.warning("Removed blocked emoji (%s).", blocked_emoji) blocked_emoji = self.config.remove("blocked_emoji") await self.config.update() return sent_emoji, blocked_emoji
Example #2
def allowed_strings(*values, preserve_case: bool = False) -> t.Callable[[str], str]: """ Return a converter which only allows arguments equal to one of the given values. Unless preserve_case is True, the argument is converted to lowercase. All values are then expected to have already been given in lowercase too. """ def converter(arg: str) -> str: if not preserve_case: arg = arg.lower() if arg not in values: raise BadArgument(f"Only the following values are allowed:n```{', '.join(values)}```") else: return arg return converter
Example #3
def convert(ctx: Context, url: str) -> str: """This converter checks whether the given URL can be reached with a status code of 200.""" try: async with ctx.bot.http_session.get(url) as resp: if resp.status != 200: raise BadArgument( f"HTTP GET on `{url}` returned status `{resp.status}`, expected 200" ) except CertificateError: if url.startswith('https'): raise BadArgument( f"Got a `CertificateError` for URL `{url}`. Does it support HTTPS?" ) raise BadArgument(f"Got a `CertificateError` for URL `{url}`.") except ValueError: raise BadArgument(f"`{url}` doesn't look like a valid hostname to me.") except ClientConnectorError: raise BadArgument(f"Cannot connect to host with URL `{url}`.") return url
Example #4
def convert(ctx: Context, sub: str) -> str: """ Force sub to begin with "r/" and check if it's a valid subreddit. If sub is a valid subreddit, return it prepended with "r/" """ sub = sub.lower() if not sub.startswith("r/"): sub = f"r/{sub}" resp = await ctx.bot.http_session.get( "https://www.reddit.com/subreddits/search.json", params={"q": sub} ) json = await resp.json() if not json["data"]["children"]: raise BadArgument( f"The subreddit `{sub}` either doesn't exist, or it has no posts." ) return sub
Example #5
def convert(ctx: Context, tag_name: str) -> str: """Lowercase & strip whitespace from proposed tag_name & ensure it's valid.""" tag_name = tag_name.lower().strip() # The tag name has at least one invalid character. if ascii(tag_name)[1:-1] != tag_name: raise BadArgument("Don't be ridiculous, you can't use that character!") # The tag name is either empty, or consists of nothing but whitespace. elif not tag_name: raise BadArgument("Tag names should not be empty, or filled with whitespace.") # The tag name is longer than 127 characters. elif len(tag_name) > 127: raise BadArgument("Are you insane? That's way too long!") # The tag name is ascii but does not contain any letters. elif not any(character.isalpha() for character in tag_name): raise BadArgument("Tag names must contain at least one letter.") return tag_name
Example #6
def convert(self, ctx: Context, argument: str) -> t.Optional[int]: """ Convert `argument` to a duration that's max 15 minutes or None. If `"forever"` is passed, None is returned; otherwise an int of the extracted time. Accepted formats are: * <duration>, * <duration>m, * <duration>M, * forever. """ if argument == "forever": return None match = self.MINUTES_RE.match(argument) if not match: raise BadArgument(f"{argument} is not a valid minutes duration.") duration = int(match.group(1)) if duration > 15: raise BadArgument("Duration must be at most 15 minutes.") return duration
Example #7
def convert(self, ctx: Context, arg: str) -> t.Union[discord.User, discord.Object]: """Convert the `arg` to a `discord.User` or `discord.Object`.""" try: return await super().convert(ctx, arg) except BadArgument: pass try: user_id = int(arg) log.trace(f"Fetching user {user_id}...") return await ctx.bot.fetch_user(user_id) except ValueError: log.debug(f"Failed to fetch user {arg}: could not convert to int.") raise BadArgument(f"The provided argument can't be turned into integer: `{arg}`") except discord.HTTPException as e: # If the Discord error isn't `Unknown user`, return a proxy instead if e.code != 10013: log.info(f"Failed to fetch user, returning a proxy instead: status {e.status}") return proxy_user(arg) log.debug(f"Failed to fetch user {arg}: user does not exist.") raise BadArgument(f"User `{arg}` does not exist")
Example #8
def on_command_error(ctx, error): send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError) if isinstance(error, commands.CommandNotFound): # fails silently pass elif isinstance(error, send_help): _help = await send_cmd_help(ctx) await ctx.send(embed=_help) elif isinstance(error, commands.CommandOnCooldown): await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s') elif isinstance(error, commands.MissingPermissions): await ctx.send('You do not have the permissions to use this command.') # If any other error occurs, prints to console. else: print(''.join(traceback.format_exception(type(error), error, error.__traceback__)))
Example #9
def convert(self, ctx, argument): message = await commands.converter.MessageConverter().convert(ctx, argument) if message.channel not in ctx.bot.cogs['Logger'].channels: raise commands.BadArgument(_('That message is not from a log channel.')) try: embed = message.embeds[0] except IndexError: raise commands.BadArgument(_('No embeds were found in that message.')) m = re.match(LINKED_EMOTE, embed.description) or re.match(utils.lexer.t_CUSTOM_EMOTE, embed.description) try: return await ctx.bot.cogs['Database'].get_emote(m['name']) except EmoteNotFoundError: d = m.groupdict() d['nsfw'] = 'MOD_NSFW' d['id'] = int(d['id']) d['animated'] = d.get('extension') == 'gif' or bool(d.get('animated')) return DatabaseEmote(d) # because MultiConverter does not support Union
Example #10
def convert(self, ctx, argument): err = None try: logged_emote = await LoggedEmote().convert(ctx, argument) except commands.CommandError as exc: pass else: return logged_emote try: db_emote = await self.db_conv.convert(ctx, argument) except commands.CommandError as exc: raise commands.BadArgument( _('Failed to interpret {argument} as a logged emote message or an emote in my database.') .format(argument=argument)) return db_emote
Example #11
def command_error(self, ctx: Context, error: CommandError) -> None: """Local error handler for the Snake Cog.""" embed = Embed() embed.colour = Colour.red() if isinstance(error, BadArgument): embed.description = str(error) embed.title = random.choice(ERROR_REPLIES) elif isinstance(error, OSError): log.error(f"snake_card encountered an OSError: {error} ({error.original})") embed.description = "Could not generate the snake card! Please try again." embed.title = random.choice(ERROR_REPLIES) else: log.error(f"Unhandled tag command error: {error} ({error.original})") return await ctx.send(embed=embed) # endregion
Example #12
def convert(self, ctx: commands.Context, coordinate: str) -> typing.Tuple[int, int]: """Take in a coordinate string and turn it into an (x, y) tuple.""" if not 2 <= len(coordinate) <= 3: raise commands.BadArgument('Invalid co-ordinate provided') coordinate = coordinate.lower() if coordinate[0].isalpha(): digit = coordinate[1:] letter = coordinate[0] else: digit = coordinate[:-1] letter = coordinate[-1] if not digit.isdigit(): raise commands.BadArgument x = ord(letter) - ord('a') y = int(digit) - 1 if (not 0 <= x <= 9) or (not 0 <= y <= 9): raise commands.BadArgument return x, y
Example #13
def dj(self, ctx, *, role): settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id) if role.lower() == "none": settings.djroleId = "NONE" await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} The DJ role has been cleared, only people with the manage server permission " f"can use DJ commands now") else: try: role = await commands.RoleConverter().convert(ctx, role) except commands.BadArgument: await ctx.send(f"{WARNING} That role was not found!") return settings.djroleId = role.id await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} DJ commands can now only be used by people who have the **{role.name}** role " f"or the manage server permission")
Example #14
def tc(self, ctx, *, channel): settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id) if channel.lower() == "none": settings.textId = "NONE" await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} The music text channel has been cleared, people can now use music commands in " f"all text channels") else: try: channel = await commands.TextChannelConverter().convert(ctx, channel) except commands.BadArgument: await ctx.send(f"{WARNING} That channel was not found!") return settings.textId = channel.id await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} Music commands can now only be used in the **{channel.name}** text channel")
Example #15
def vc(self, ctx, *, channel): settings = await SettingsDB.get_instance().get_guild_settings(ctx.guild.id) if channel.lower() == "none": settings.voiceId = "NONE" await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} The music voice channel has been cleared, people can now play music in all " f"channels") else: try: channel = await commands.VoiceChannelConverter().convert(ctx, channel) except commands.BadArgument: await ctx.send(f"{WARNING} That channel was not found!") return settings.voiceId = channel.id await SettingsDB.get_instance().set_guild_settings(settings) await ctx.send(f"{SUCCESS} Music can now only be played in the **{channel.name}** voice channel")
Example #16
def on_command_error(self, ctx, exception): exc_class = exception.__class__ if exc_class in (commands.CommandNotFound, commands.NotOwner): return exc_table = { commands.MissingRequiredArgument: f"{WARNING} The required arguments are missing for this command!", commands.NoPrivateMessage: f"{WARNING} This command cannot be used in PM's!", commands.BadArgument: f"{WARNING} A bad argument was passed, please check if your arguments are correct!", IllegalAction: f"{WARNING} A node error has occurred: `{getattr(exception, 'msg', None)}`", CustomCheckFailure: getattr(exception, "msg", None) or "None" } if exc_class in exc_table.keys(): await ctx.send(exc_table[exc_class]) else: await super().on_command_error(ctx, exception)
Example #17
def test_tag_content_converter_for_invalid(self): """TagContentConverter should raise the proper exception for invalid input.""" test_values = ( ('', "Tag contents should not be empty, or filled with whitespace."), (' ', "Tag contents should not be empty, or filled with whitespace."), ) for value, exception_message in test_values: with self.subTest(tag_content=value, exception_message=exception_message): with self.assertRaisesRegex(BadArgument, re.escape(exception_message)): await TagContentConverter.convert(self.context, value)
Example #18
def test_valid_python_identifier_for_invalid(self): """ValidPythonIdentifier raises the proper exception for invalid identifiers.""" test_values = ('nested.stuff', '#####') for name in test_values: with self.subTest(identifier=name): exception_message = f'`{name}` is not a valid Python identifier' with self.assertRaisesRegex(BadArgument, re.escape(exception_message)): await ValidPythonIdentifier.convert(self.context, name)
Example #19
def test_duration_converter_for_invalid(self): """Duration raises the right exception for invalid duration strings.""" test_values = ( # Units in wrong order '1d1w', '1s1y', # Duplicated units '1 year 2 years', '1 M 10 minutes', # Unknown substrings '1MVes', '1y3breads', # Missing amount 'ym', # Incorrect whitespace " 1y", "1S ", "1y 1m", # Garbage 'Guido van Rossum', 'lemon lemon lemon lemon lemon lemon lemon', ) converter = Duration() for invalid_duration in test_values: with self.subTest(invalid_duration=invalid_duration): exception_message = f'`{invalid_duration}` is not a valid duration string.' with self.assertRaisesRegex(BadArgument, re.escape(exception_message)): await converter.convert(self.context, invalid_duration)
Example #20
def test_duration_converter_out_of_range(self, mock_datetime): """Duration converter should raise BadArgument if datetime raises a ValueError.""" mock_datetime.__add__.side_effect = ValueError mock_datetime.utcnow.return_value = mock_datetime duration = f"{datetime.MAXYEAR}y" exception_message = f"`{duration}` results in a datetime outside the supported range." with self.assertRaisesRegex(BadArgument, re.escape(exception_message)): await Duration().convert(self.context, duration)
Example #21
def test_hush_duration_converter_for_invalid(self): """HushDurationConverter raises correct exception for invalid minutes duration strings.""" test_values = ( ("16", "Duration must be at most 15 minutes."), ("10d", "10d is not a valid minutes duration."), ("-1", "-1 is not a valid minutes duration."), ) converter = HushDurationConverter() for invalid_minutes_string, exception_message in test_values: with self.subTest(invalid_minutes_string=invalid_minutes_string, exception_message=exception_message): with self.assertRaisesRegex(BadArgument, re.escape(exception_message)): await converter.convert(self.context, invalid_minutes_string)
Example #22
def convert(self, ctx: Context, argument: str) -> str: """Fully qualify the name of an extension and ensure it exists.""" # Special values to reload all extensions if argument == "*" or argument == "**": return argument argument = argument.lower() if "." not in argument: argument = f"bot.cogs.{argument}" if argument in EXTENSIONS: return argument else: raise commands.BadArgument(f":x: Could not find the extension `{argument}`.")
Example #23
def cog_command_error(self, ctx: Context, error: Exception) -> None: """Handle BadArgument errors locally to prevent the help command from showing.""" if isinstance(error, commands.BadArgument): await ctx.send(str(error)) error.handled = True
Example #24
def convert(ctx: Context, argument: str) -> str: """Checks whether the given string is a valid Python identifier.""" if not argument.isidentifier(): raise BadArgument(f"`{argument}` is not a valid Python identifier") return argument
Example #25
def convert(self, ctx: Context, duration: str) -> datetime: """ Converts a `duration` string to a datetime object that's `duration` in the future. The converter supports the following symbols for each unit of time: - years: `Y`, `y`, `year`, `years` - months: `m`, `month`, `months` - weeks: `w`, `W`, `week`, `weeks` - days: `d`, `D`, `day`, `days` - hours: `H`, `h`, `hour`, `hours` - minutes: `M`, `minute`, `minutes` - seconds: `S`, `s`, `second`, `seconds` The units need to be provided in descending order of magnitude. """ match = self.duration_parser.fullmatch(duration) if not match: raise BadArgument(f"`{duration}` is not a valid duration string.") duration_dict = {unit: int(amount) for unit, amount in match.groupdict(default=0).items()} delta = relativedelta(**duration_dict) now = datetime.utcnow() try: return now + delta except ValueError: raise BadArgument(f"`{duration}` results in a datetime outside the supported range.")
Example #26
def convert(self, ctx: Context, datetime_string: str) -> datetime: """ Converts a ISO-8601 `datetime_string` into a `datetime.datetime` object. The converter is flexible in the formats it accepts, as it uses the `isoparse` method of `dateutil.parser`. In general, it accepts datetime strings that start with a date, optionally followed by a time. Specifying a timezone offset in the datetime string is supported, but the `datetime` object will be converted to UTC and will be returned without `tzinfo` as a timezone-unaware `datetime` object. See: https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse Formats that are guaranteed to be valid by our tests are: - `YYYY-mm-ddTHH:MM:SSZ` | `YYYY-mm-dd HH:MM:SSZ` - `YYYY-mm-ddTHH:MM:SS±HH:MM` | `YYYY-mm-dd HH:MM:SS±HH:MM` - `YYYY-mm-ddTHH:MM:SS±HHMM` | `YYYY-mm-dd HH:MM:SS±HHMM` - `YYYY-mm-ddTHH:MM:SS±HH` | `YYYY-mm-dd HH:MM:SS±HH` - `YYYY-mm-ddTHH:MM:SS` | `YYYY-mm-dd HH:MM:SS` - `YYYY-mm-ddTHH:MM` | `YYYY-mm-dd HH:MM` - `YYYY-mm-dd` - `YYYY-mm` - `YYYY` Note: ISO-8601 specifies a `T` as the separator between the date and the time part of the datetime string. The converter accepts both a `T` and a single space character. """ try: dt = dateutil.parser.isoparse(datetime_string) except ValueError: raise BadArgument(f"`{datetime_string}` is not a valid ISO-8601 datetime string") if dt.tzinfo: dt = dt.astimezone(dateutil.tz.UTC) dt = dt.replace(tzinfo=None) return dt
Example #27
def proxy_user(user_id: str) -> discord.Object: """ Create a proxy user object from the given id. Used when a Member or User object cannot be resolved. """ log.trace(f"Attempting to create a proxy user for the user id {user_id}.") try: user_id = int(user_id) except ValueError: log.debug(f"Failed to create proxy user {user_id}: could not convert to int.") raise BadArgument(f"User ID `{user_id}` is invalid - could not convert to an integer.") user = discord.Object(user_id) user.mention = user.id user.display_name = f"<@{user.id}>" user.avatar_url_as = lambda static_format: None user.bot = False return user
Example #28
def convert(self, ctx, argument): argument = argument.replace(",", "").strip("$") if not argument.strip("-").replace(".", "").isdigit(): raise commands.BadArgument("That is not a number!") if len(argument) > 10: raise commands.BadArgument("That number is much too big! Must be less than 999,999,999") return round(float(argument), 2)
Example #29
def convert(self, ctx, argument): argument = argument.replace(",", "").strip("$") if not argument.strip("-").replace(".", "").isdigit(): raise commands.BadArgument("That is not a number!") if len(argument) > 10: raise commands.BadArgument("That number is much too big! Must be less than 999,999,999") return int(argument)
Example #30
def convert(self, ctx, argument): fargument = argument.replace(",", "").strip("$") if not fargument.strip("-").replace(".", "").isdigit(): if "x" in argument: item, n = argument.split("x") if n.isdigit(): return item, int(n) return argument if len(fargument) > 10: raise commands.BadArgument("That number is much too big! Must be less than 999,999,999") return round(float(fargument), 2)