The ErrorEvent
interface represents events providing information related to errors in scripts or in files.
Event
ErrorEvent
Instance properties
Also inherits properties from its parent Event
.
ErrorEvent.message
Read only-
A string containing a human-readable error message describing the problem. Lacking a
crossorigin
setting reduces error logging. ErrorEvent.filename
Read only-
A string containing the name of the script file in which the error occurred.
ErrorEvent.lineno
Read only-
An
integer
containing the line number of the script file on which the error occurred. ErrorEvent.colno
Read only-
An
integer
containing the column number of the script file on which the error occurred. ErrorEvent.error
Read only-
A JavaScript
Object
that is concerned by the event.
Constructor
ErrorEvent()
-
Creates an
ErrorEvent
event with the given parameters.
Instance methods
Inherits methods from its parent Event
.
Specifications
Specification |
---|
HTML Standard # the-errorevent-interface |
Browser compatibility
BCD tables only load in the browser
See also
- Using web workers, most likely objects to raise such an event
Ошибки¶
Приложения, работающие в Node.js, обычно сталкиваются с четырьмя категориями ошибок:
- Стандартные ошибки JavaScript, такие как {EvalError}, {SyntaxError}, {RangeError}, {ReferenceError}, {TypeError} и {URIError}.
- Системные ошибки, вызванные ограничениями базовой операционной системы, такими как попытка открыть несуществующий файл или попытка отправить данные через закрытый сокет.
- Пользовательские ошибки, вызванные кодом приложения.
AssertionError
s — это особый класс ошибок, который может быть вызван, когда Node.js обнаруживает исключительное логическое нарушение, которое никогда не должно происходить. Обычно они поднимаютсяassert
модуль.
Все ошибки JavaScript и системные ошибки, вызванные Node.js, наследуются от стандартного класса {Error} JavaScript или являются его экземплярами и гарантированно предоставляют по меньшей мере свойства, доступные в этом классе.
Распространение ошибок и перехват¶
Node.js поддерживает несколько механизмов распространения и обработки ошибок, возникающих во время работы приложения. То, как эти ошибки сообщаются и обрабатываются, полностью зависит от типа Error
и стиль вызываемого API.
Все ошибки JavaScript обрабатываются как исключения, которые немедленно генерировать и выдавать ошибку с помощью стандартного JavaScript throw
механизм. Они обрабатываются с помощью try…catch
строить предоставляется языком JavaScript.
// Throws with a ReferenceError because z is not defined.
try {
const m = 1;
const n = m + z;
} catch (err) {
// Handle the error here.
}
Любое использование JavaScript throw
механизм вызовет исключение, которое должен обрабатываться с использованием try…catch
или процесс Node.js немедленно завершится.
За некоторыми исключениями, Синхронный API (любой метод блокировки, не принимающий callback
функция, например fs.readFileSync
), буду использовать throw
сообщать об ошибках.
Ошибки, возникающие внутри Асинхронные API можно сообщить несколькими способами:
- Большинство асинхронных методов, которые принимают
callback
функция приметError
объект, переданный в качестве первого аргумента этой функции. Если этот первый аргумент неnull
и является экземпляромError
, то произошла ошибка, которую необходимо обработать.
const fs = require('fs');
fs.readFile('a file that does not exist', (err, data) => {
if (err) {
console.error(
'There was an error reading the file!',
err
);
return;
}
// Otherwise handle the data
});
- Когда асинхронный метод вызывается для объекта, который является
EventEmitter
, ошибки могут быть перенаправлены на этот объект'error'
событие.
const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
// If the connection is reset by the server, or if it can't
// connect at all, or on any sort of error encountered by
// the connection, the error will be sent here.
console.error(err);
});
connection.pipe(process.stdout);
- Некоторые обычно асинхронные методы в API Node.js могут по-прежнему использовать
throw
механизм для создания исключений, которые должны обрабатываться с помощьюtry…catch
. Исчерпывающего списка таких методов нет; обратитесь к документации по каждому методу, чтобы определить соответствующий требуемый механизм обработки ошибок.
Использование 'error'
механизм событий наиболее распространен для потоковый а также на основе эмиттера событий API-интерфейсы, которые сами по себе представляют собой серию асинхронных операций с течением времени (в отличие от одной операции, которая может пройти или закончиться неудачей).
Для все EventEmitter
объекты, если 'error'
обработчик событий не предоставляется, будет выдана ошибка, в результате чего процесс Node.js сообщит о неперехваченном исключении и завершится сбоем, если только одно из следующих событий: domain
модуль используется надлежащим образом или обработчик зарегистрирован для 'uncaughtException'
событие.
const EventEmitter = require('events');
const ee = new EventEmitter();
setImmediate(() => {
// This will crash the process because no 'error' event
// handler has been added.
ee.emit('error', new Error('This will crash'));
});
Ошибки, сгенерированные таким образом не мочь быть перехваченным с помощью try…catch
как они брошены после код вызова уже вышел.
Разработчики должны обращаться к документации по каждому методу, чтобы точно определить, как распространяются ошибки, вызванные этими методами.
Обратные вызовы при первой ошибке¶
Большинство асинхронных методов, предоставляемых основным API Node.js, следуют идиоматическому шаблону, называемому обратный вызов при первой ошибке. В этом шаблоне функция обратного вызова передается методу в качестве аргумента. Когда операция завершается или возникает ошибка, вызывается функция обратного вызова с Error
объект (если есть) передается в качестве первого аргумента. Если ошибки не возникло, первый аргумент будет передан как null
.
const fs = require('fs');
function errorFirstCallback(err, data) {
if (err) {
console.error('There was an error', err);
return;
}
console.log(data);
}
fs.readFile(
'/some/file/that/does-not-exist',
errorFirstCallback
);
fs.readFile(
'/some/file/that/does-exist',
errorFirstCallback
);
JavaScript try…catch
механизм не мочь использоваться для перехвата ошибок, генерируемых асинхронными API. Распространенная ошибка новичков — пытаться использовать throw
внутри обратного вызова с ошибкой:
// THIS WILL NOT WORK:
const fs = require('fs');
try {
fs.readFile(
'/some/file/that/does-not-exist',
(err, data) => {
// Mistaken assumption: throwing here...
if (err) {
throw err;
}
}
);
} catch (err) {
// This will not catch the throw!
console.error(err);
}
Это не сработает, потому что функция обратного вызова передана в fs.readFile()
вызывается асинхронно. К моменту вызова обратного вызова окружающий код, включая try…catch
блок, уже вышли. Выдача ошибки внутри обратного вызова может привести к сбою процесса Node.js в большинстве случаев. Если домены включены, или обработчик был зарегистрирован с process.on('uncaughtException')
, такие ошибки можно перехватить.
Класс: Error
¶
Общий объект JavaScript {Error}, не указывающий на конкретную причину возникновения ошибки. Error
объекты фиксируют «трассировку стека», детализирующую точку в коде, в которой Error
был создан, и может содержать текстовое описание ошибки.
Все ошибки, генерируемые Node.js, включая все системные ошибки и ошибки JavaScript, будут либо экземплярами, либо унаследованы от Error
класс.
new Error(message)
¶
message
{нить}
Создает новый Error
объект и устанавливает error.message
в предоставленное текстовое сообщение. Если объект передается как message
, текстовое сообщение создается при вызове message.toString()
. В error.stack
свойство будет представлять точку в коде, в которой new Error()
назывался. Трассировки стека зависят от API трассировки стека V8. Трассировки стека распространяются только на (а) начало синхронное выполнение кода, или (b) количество кадров, заданное свойством Error.stackTraceLimit
, в зависимости от того, что меньше.
Error.captureStackTrace(targetObject[, constructorOpt])
¶
targetObject
{Объект}constructorOpt
{Функция}
Создает .stack
собственность на targetObject
, который при доступе возвращает строку, представляющую место в коде, в котором Error.captureStackTrace()
назывался.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
Первая строка трассировки будет иметь префикс ${myObject.name}: ${myObject.message}
.
Необязательный constructorOpt
Аргумент принимает функцию. Если указано, все кадры выше constructorOpt
, включая constructorOpt
, будет исключен из сгенерированной трассировки стека.
В constructorOpt
Аргумент полезен для сокрытия деталей реализации генерации ошибок от пользователя. Например:
function MyError() {
Error.captureStackTrace(this, MyError);
}
// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;
Error.stackTraceLimit
¶
- {количество}
В Error.stackTraceLimit
указывает количество кадров стека, собранных трассировкой стека (независимо от того, сгенерированы ли они new Error().stack
или Error.captureStackTrace(obj)
).
Значение по умолчанию — 10
но может быть установлен на любой допустимый номер JavaScript. Изменения повлияют на любую записанную трассировку стека. после значение было изменено.
Если установлено нечисловое значение или задано отрицательное число, трассировки стека не будут захватывать какие-либо кадры.
error.code
¶
- {нить}
В error.code
Свойство — это строковая метка, определяющая тип ошибки. error.code
это наиболее стабильный способ выявления ошибки. Он будет меняться только между основными версиями Node.js. Наоборот, error.message
строки могут меняться между любыми версиями Node.js. Видеть Коды ошибок Node.js для получения подробной информации о конкретных кодах.
error.message
¶
- {нить}
В error.message
свойство — это строковое описание ошибки, установленное при вызове new Error(message)
. В message
переданный конструктору, также появится в первой строке трассировки стека Error
, однако изменение этого свойства после Error
объект создан может нет изменить первую строку трассировки стека (например, когда error.stack
читается до изменения этого свойства).
const err = new Error('The message');
console.error(err.message);
// Prints: The message
error.stack
¶
- {нить}
В error.stack
свойство — это строка, описывающая точку в коде, в которой Error
был создан.
Error: Things keep happening!
at /home/gbusey/file.js:525:2
at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
at increaseSynergy (/home/gbusey/actors.js:701:6)
Первая строка отформатирована как <error class name>: <error message>
, за которым следует серия кадров стека (каждая строка начинается с «at»). Каждый фрейм описывает сайт вызова в коде, который приводит к сгенерированной ошибке. V8 пытается отобразить имя для каждой функции (по имени переменной, имени функции или имени метода объекта), но иногда не может найти подходящее имя. Если V8 не может определить имя функции, для этого фрейма будет отображаться только информация о местоположении. В противном случае определенное имя функции будет отображаться с информацией о местоположении, добавленной в круглые скобки.
Фреймы создаются только для функций JavaScript. Если, например, выполнение синхронно проходит через дополнительную функцию C ++, называемую cheetahify
который сам вызывает функцию JavaScript, фрейм, представляющий cheetahify
вызов не будет присутствовать в трассировке стека:
const cheetahify = require('./native-binding.node');
function makeFaster() {
// `cheetahify()` *synchronously* calls speedy.
cheetahify(function speedy() {
throw new Error('oh no!');
});
}
makeFaster();
// will throw:
// /home/gbusey/file.js:6
// throw new Error('oh no!');
// ^
// Error: oh no!
// at speedy (/home/gbusey/file.js:6:11)
// at makeFaster (/home/gbusey/file.js:5:3)
// at Object.<anonymous> (/home/gbusey/file.js:10:1)
// at Module._compile (module.js:456:26)
// at Object.Module._extensions..js (module.js:474:10)
// at Module.load (module.js:356:32)
// at Function.Module._load (module.js:312:12)
// at Function.Module.runMain (module.js:497:10)
// at startup (node.js:119:16)
// at node.js:906:3
Информация о местоположении будет одной из следующих:
native
, если кадр представляет внутренний вызов V8 (как в[].forEach
).plain-filename.js:line:column
, если фрейм представляет собой внутренний вызов Node.js./absolute/path/to/file.js:line:column
, если кадр представляет собой вызов в пользовательской программе или ее зависимостях.
Строка, представляющая трассировку стека, генерируется лениво, когда error.stack
собственность доступ.
Количество кадров, захваченных трассировкой стека, ограничено меньшим из Error.stackTraceLimit
или количество доступных кадров в текущем тике цикла событий.
Класс: AssertionError
¶
- Расширяется: {errors.Error}
Указывает на неудачу утверждения. Подробнее см. Class: assert.AssertionError
.
Класс: RangeError
¶
- Расширяется: {errors.Error}
Указывает, что предоставленный аргумент находится за пределами набора или диапазона допустимых значений для функции; является ли это числовым диапазоном или вне набора опций для данного параметра функции.
require('net').connect(-1);
// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
Node.js сгенерирует и выбросит RangeError
экземпляры немедленно как форма подтверждения аргумента.
Класс: ReferenceError
¶
- Расширяется: {errors.Error}
Указывает, что предпринимается попытка получить доступ к переменной, которая не определена. Такие ошибки обычно указывают на опечатки в коде или на некорректную программу.
Хотя клиентский код может генерировать и распространять эти ошибки, на практике это будет делать только V8.
doesNotExist;
// Throws ReferenceError, doesNotExist is not a variable in this program.
Если приложение динамически не генерирует и не запускает код, ReferenceError
экземпляры указывают на ошибку в коде или его зависимостях.
Класс: SyntaxError
¶
- Расширяется: {errors.Error}
Указывает, что программа не является допустимым JavaScript. Эти ошибки могут возникать и распространяться только в результате оценки кода. Оценка кода может произойти в результате eval
, Function
, require
, или vm. Эти ошибки почти всегда указывают на неработающую программу.
try {
require('vm').runInThisContext('binary ! isNotOk');
} catch (err) {
// 'err' will be a SyntaxError.
}
SyntaxError
экземпляры невозможно восстановить в контексте, который их создал — они могут быть перехвачены только в других контекстах.
Класс: SystemError
¶
- Расширяется: {errors.Error}
Node.js генерирует системные ошибки, когда в среде выполнения возникают исключения. Обычно это происходит, когда приложение нарушает ограничение операционной системы. Например, системная ошибка произойдет, если приложение попытается прочитать несуществующий файл.
address
{строка} Если присутствует, адрес, к которому не удалось подключиться к сети.code
{строка} Код ошибки строкиdest
{строка} Если присутствует, путь к файлу при сообщении об ошибке файловой системыerrno
{number} Номер ошибки, предоставленный системойinfo
{Object} Если присутствует, дополнительные сведения о состоянии ошибкиmessage
{string} Предоставляемое системой описание ошибки в удобной для чтения форме.path
{строка} Если присутствует, путь к файлу при сообщении об ошибке файловой системыport
{number} Если присутствует, порт сетевого подключения, который недоступенsyscall
{строка} Имя системного вызова, вызвавшего ошибку
error.address
¶
- {нить}
Если представить, error.address
— это строка, описывающая адрес, к которому не удалось установить сетевое соединение.
error.code
¶
- {нить}
В error.code
свойство — это строка, представляющая код ошибки.
error.dest
¶
- {нить}
Если представить, error.dest
— это путь к файлу при сообщении об ошибке файловой системы.
error.errno
¶
- {количество}
В error.errno
свойство — отрицательное число, которое соответствует коду ошибки, определенному в libuv Error handling
.
В Windows номер ошибки, предоставленный системой, будет нормализован libuv.
Чтобы получить строковое представление кода ошибки, используйте util.getSystemErrorName(error.errno)
.
error.info
¶
- {Объект}
Если представить, error.info
— объект с подробной информацией о состоянии ошибки.
error.message
¶
- {нить}
error.message
представляет собой удобочитаемое описание ошибки, предоставляемое системой.
error.path
¶
- {нить}
Если представить, error.path
— строка, содержащая соответствующий недопустимый путь.
error.port
¶
- {количество}
Если представить, error.port
порт сетевого подключения недоступен.
error.syscall
¶
- {нить}
В error.syscall
свойство — это строка, описывающая системный вызов это не удалось.
Общие системные ошибки¶
Это список системных ошибок, которые часто встречаются при написании программы на Node.js. Полный список см. В errno
(3) справочная страница.
-
EACCES
(В разрешении отказано): была сделана попытка получить доступ к файлу способом, запрещенным его разрешениями на доступ к файлу. -
EADDRINUSE
(Адрес уже используется): попытка привязать сервер (net
,http
, илиhttps
) на локальный адрес не удалось из-за того, что другой сервер в локальной системе уже занимает этот адрес. -
ECONNREFUSED
(В соединении отказано): соединение не может быть установлено, потому что целевая машина активно отказалась от него. Обычно это происходит из-за попытки подключиться к неактивной службе на чужом хосте. -
ECONNRESET
(Сброс соединения одноранговым узлом): соединение было принудительно закрыто одноранговым узлом. Обычно это происходит из-за потери соединения с удаленным сокетом из-за тайм-аута или перезагрузки. Обычно встречается черезhttp
а такжеnet
модули. -
EEXIST
(Файл существует): существующий файл был целью операции, которая требовала, чтобы цель не существовала. -
EISDIR
(Является каталогом): операция ожидала файл, но указанный путь был каталогом. -
EMFILE
(Слишком много открытых файлов в системе): максимальное количество файловые дескрипторы допустимый в системе, и запросы для другого дескриптора не могут быть выполнены, пока хотя бы один из них не будет закрыт. Это происходит при одновременном открытии множества файлов одновременно, особенно в системах (в частности, macOS), где существует низкий предел дескрипторов файлов для процессов. Чтобы исправить низкий предел, запуститеulimit -n 2048
в той же оболочке, которая будет запускать процесс Node.js. -
ENOENT
(Нет такого файла или каталога): обычно создаетсяfs
операции, чтобы указать, что компонент указанного пути не существует. По указанному пути не удалось найти ни один объект (файл или каталог). -
ENOTDIR
(Не каталог): компонент с указанным путем существует, но не является каталогом, как ожидалось. Обычно выращиваетсяfs.readdir
. -
ENOTEMPTY
(Каталог не пустой): каталог с записями был целью операции, для которой требуется пустой каталог, обычноfs.unlink
. -
ENOTFOUND
(Ошибка поиска DNS): указывает на сбой DNS либоEAI_NODATA
илиEAI_NONAME
. Это не стандартная ошибка POSIX. -
EPERM
(Операция запрещена): была сделана попытка выполнить операцию, требующую повышенных привилегий. -
EPIPE
(Сломанный канал): запись в канал, сокет или FIFO, для которого нет процесса для чтения данных. Часто встречается наnet
а такжеhttp
Уровни, указывающие на то, что удаленная сторона записываемого потока была закрыта. -
ETIMEDOUT
(Превышено время ожидания операции): запрос на подключение или отправку завершился неудачно, поскольку подключенная сторона не ответила должным образом по прошествии определенного периода времени. Обычно встречаетсяhttp
илиnet
. Часто признак того, чтоsocket.end()
не был должным образом назван.
Класс: TypeError
¶
- Расширяет {errors.Error}
Указывает, что указанный аргумент не является допустимым типом. Например, передача функции параметру, который ожидает строку, будет TypeError
.
require('url').parse(() => {});
// Throws TypeError, since it expected a string.
Node.js сгенерирует и выбросит TypeError
экземпляры немедленно как форма подтверждения аргумента.
Исключения против ошибок¶
Исключение JavaScript — это значение, которое выбрасывается в результате недопустимой операции или как цель throw
утверждение. Хотя не требуется, чтобы эти значения были экземплярами Error
или классы, которые наследуются от Error
, все исключения, создаваемые Node.js или средой выполнения JavaScript буду быть экземплярами Error
.
Некоторые исключения безвозвратно на уровне JavaScript. Такие исключения будут всегда вызвать сбой процесса Node.js. Примеры включают assert()
чеки или abort()
вызывает в слое C ++.
Ошибки OpenSSL¶
Ошибки, возникающие в crypto
или tls
классные Error
, и в дополнение к стандартному .code
а также .message
properties, могут иметь некоторые дополнительные свойства, специфичные для OpenSSL.
error.opensslErrorStack
¶
Массив ошибок, который может дать контекст, откуда в библиотеке OpenSSL возникла ошибка.
error.function
¶
Функция OpenSSL, в которой возникла ошибка.
error.library
¶
Библиотека OpenSSL, в которой возникла ошибка.
error.reason
¶
Строка в удобном для чтения виде, описывающая причину ошибки.
ABORT_ERR
¶
Используется, когда операция была прервана (обычно с использованием AbortController
).
API нет с использованием AbortSignal
s обычно не вызывают ошибки с этим кодом.
Этот код не использует обычный ERR_*
соглашение об ошибках Node.js используется для обеспечения совместимости с веб-платформой. AbortError
.
ERR_AMBIGUOUS_ARGUMENT
¶
Аргумент функции используется таким образом, чтобы предположить, что сигнатура функции может быть неправильно понята. Это брошено assert
модуль, когда message
параметр в assert.throws(block, message)
совпадает с сообщением об ошибке, выданным block
потому что это использование предполагает, что пользователь верит message
ожидаемое сообщение, а не сообщение AssertionError
будет отображаться, если block
не бросает.
ERR_ARG_NOT_ITERABLE
¶
Итерируемый аргумент (т.е. значение, которое работает с for...of
loops) требуется, но не предоставляется API Node.js.
ERR_ASSERTION
¶
Особый тип ошибки, которая может быть вызвана всякий раз, когда Node.js обнаруживает исключительное логическое нарушение, которое никогда не должно происходить. Обычно они поднимаются assert
модуль.
ERR_ASYNC_CALLBACK
¶
Была сделана попытка зарегистрировать что-то, что не является функцией, как AsyncHooks
Перезвоните.
ERR_ASYNC_TYPE
¶
Недопустимый тип асинхронного ресурса. Пользователи также могут определять свои собственные типы при использовании общедоступного API для встраивания.
ERR_BROTLI_COMPRESSION_FAILED
¶
Данные, переданные в поток Brotli, не были успешно сжаты.
ERR_BROTLI_INVALID_PARAM
¶
Во время построения потока Brotli был передан недопустимый ключ параметра.
ERR_BUFFER_CONTEXT_NOT_AVAILABLE
¶
Была сделана попытка создать Node.js Buffer
из кода надстройки или встраивания, находясь в контексте механизма JS, который не связан с экземпляром Node.js. Данные, переданные в Buffer
будет выпущен к тому времени, когда метод вернется.
При возникновении этой ошибки возможная альтернатива созданию Buffer
пример — создать нормальный Uint8Array
, который отличается только прототипом результирующего объекта. Uint8Array
s общеприняты во всех основных API Node.js, где Buffer
s есть; они доступны во всех контекстах.
ERR_BUFFER_OUT_OF_BOUNDS
¶
Операция за пределами Buffer
была предпринята попытка.
ERR_BUFFER_TOO_LARGE
¶
Была сделана попытка создать Buffer
больше максимально допустимого размера.
ERR_CANNOT_WATCH_SIGINT
¶
Node.js не смог отследить SIGINT
сигнал.
ERR_CHILD_CLOSED_BEFORE_REPLY
¶
Дочерний процесс был закрыт до того, как родительский процесс получил ответ.
ERR_CHILD_PROCESS_IPC_REQUIRED
¶
Используется, когда дочерний процесс разветвляется без указания канала IPC.
ERR_CHILD_PROCESS_STDIO_MAXBUFFER
¶
Используется, когда основной процесс пытается прочитать данные из STDERR / STDOUT дочернего процесса, и длина данных больше, чем maxBuffer
вариант.
ERR_CLOSED_MESSAGE_PORT
¶
Была попытка использовать MessagePort
экземпляр в закрытом состоянии, обычно после .close()
был вызван.
ERR_CONSOLE_WRITABLE_STREAM
¶
Console
был создан без stdout
поток, или Console
имеет незаписываемый stdout
или stderr
транслировать.
ERR_CONSTRUCT_CALL_INVALID
¶
Был вызван конструктор класса, который нельзя вызвать.
ERR_CONSTRUCT_CALL_REQUIRED
¶
Конструктор класса был вызван без new
.
ERR_CONTEXT_NOT_INITIALIZED
¶
Контекст vm, переданный в API, еще не инициализирован. Это может произойти при возникновении (и обнаружении) ошибки во время создания контекста, например, при сбое выделения или при достижении максимального размера стека вызовов при создании контекста.
ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED
¶
Был запрошен механизм сертификатов клиента, который не поддерживается используемой версией OpenSSL.
ERR_CRYPTO_ECDH_INVALID_FORMAT
¶
Недопустимое значение для format
аргумент был передан crypto.ECDH()
класс getPublicKey()
метод.
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY
¶
Недопустимое значение для key
аргумент был передан crypto.ECDH()
класс computeSecret()
метод. Это означает, что открытый ключ лежит за пределами эллиптической кривой.
ERR_CRYPTO_ENGINE_UNKNOWN
¶
Неверный идентификатор криптографической машины был передан в require('crypto').setEngine()
.
ERR_CRYPTO_FIPS_FORCED
¶
В --force-fips
был использован аргумент командной строки, но была попытка включить или отключить режим FIPS в crypto
модуль.
ERR_CRYPTO_FIPS_UNAVAILABLE
¶
Была сделана попытка включить или отключить режим FIPS, но режим FIPS был недоступен.
ERR_CRYPTO_HASH_FINALIZED
¶
hash.digest()
вызвали несколько раз. В hash.digest()
метод должен вызываться не более одного раза для каждого экземпляра Hash
объект.
ERR_CRYPTO_HASH_UPDATE_FAILED
¶
hash.update()
не удалось по какой-либо причине. Это должно происходить редко, если вообще когда-либо случаться.
ERR_CRYPTO_INCOMPATIBLE_KEY
¶
Указанные криптографические ключи несовместимы с предпринятой операцией.
ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS
¶
Выбранная кодировка открытого или закрытого ключа несовместима с другими параметрами.
ERR_CRYPTO_INITIALIZATION_FAILED
¶
Не удалось инициализировать криптоподсистему.
ERR_CRYPTO_INVALID_AUTH_TAG
¶
Предоставлен недопустимый тег аутентификации.
ERR_CRYPTO_INVALID_COUNTER
¶
Для шифра режима противодействия предоставлен неверный счетчик.
ERR_CRYPTO_INVALID_CURVE
¶
Была предоставлена неверная эллиптическая кривая.
ERR_CRYPTO_INVALID_DIGEST
¶
Недействительный алгоритм криптодайджеста было указано.
ERR_CRYPTO_INVALID_IV
¶
Предоставлен недопустимый вектор инициализации.
ERR_CRYPTO_INVALID_JWK
¶
Был предоставлен недопустимый веб-ключ JSON.
ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE
¶
Данный тип объекта криптографического ключа недопустим для выполняемой операции.
ERR_CRYPTO_INVALID_KEYLEN
¶
Была предоставлена неверная длина ключа.
ERR_CRYPTO_INVALID_KEYPAIR
¶
Была предоставлена неверная пара ключей.
ERR_CRYPTO_INVALID_KEYTYPE
¶
Предоставлен недопустимый тип ключа.
ERR_CRYPTO_INVALID_MESSAGELEN
¶
Была предоставлена неверная длина сообщения.
ERR_CRYPTO_INVALID_SCRYPT_PARAMS
¶
Были предоставлены неверные параметры алгоритма шифрования.
ERR_CRYPTO_INVALID_STATE
¶
Крипто-метод был использован для объекта, находившегося в недопустимом состоянии. Например, позвонив cipher.getAuthTag()
перед звонком cipher.final()
.
ERR_CRYPTO_INVALID_TAG_LENGTH
¶
Предоставлена неверная длина тега аутентификации.
ERR_CRYPTO_JOB_INIT_FAILED
¶
Не удалось инициализировать асинхронную криптооперацию.
ERR_CRYPTO_JWK_UNSUPPORTED_CURVE
¶
Эллиптическая кривая Ключа не зарегистрирована для использования в Реестр эллиптических кривых веб-ключей JSON.
ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE
¶
Тип асимметричного ключа ключа не зарегистрирован для использования в Реестр типов веб-ключей JSON.
ERR_CRYPTO_OPERATION_FAILED
¶
Криптооперация завершилась неудачно по неустановленной причине.
ERR_CRYPTO_PBKDF2_ERROR
¶
Алгоритм PBKDF2 завершился неудачно по неустановленным причинам. OpenSSL не предоставляет более подробной информации, и, следовательно, Node.js.
ERR_CRYPTO_SCRYPT_INVALID_PARAMETER
¶
Один или больше crypto.scrypt()
или crypto.scryptSync()
параметры находятся за пределами допустимого диапазона.
ERR_CRYPTO_SCRYPT_NOT_SUPPORTED
¶
Node.js был скомпилирован без scrypt
служба поддержки. Невозможно с официальными двоичными файлами выпуска, но может произойти с пользовательскими сборками, включая сборки дистрибутива.
ERR_CRYPTO_SIGN_KEY_REQUIRED
¶
Подпись key
не был предоставлен sign.sign()
метод.
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH
¶
crypto.timingSafeEqual()
был вызван с Buffer
, TypedArray
, или DataView
аргументы разной длины.
ERR_CRYPTO_UNKNOWN_CIPHER
¶
Указан неизвестный шифр.
ERR_CRYPTO_UNKNOWN_DH_GROUP
¶
Было дано неизвестное название группы Диффи-Хеллмана. Видеть crypto.getDiffieHellman()
для списка допустимых имен групп.
ERR_CRYPTO_UNSUPPORTED_OPERATION
¶
Была сделана попытка вызвать неподдерживаемую криптографическую операцию.
ERR_DEBUGGER_ERROR
¶
Произошла ошибка с отладчик.
ERR_DEBUGGER_STARTUP_ERROR
¶
В отладчик истекло время ожидания освобождения необходимого хоста / порта.
ERR_DLOPEN_DISABLED
¶
Загрузка собственных надстроек отключена с помощью --no-addons
.
ERR_DLOPEN_FAILED
¶
Звонок в process.dlopen()
не смогли.
ERR_DIR_CLOSED
¶
В fs.Dir
ранее был закрыт.
ERR_DIR_CONCURRENT_OPERATION
¶
Была предпринята попытка синхронного чтения или закрытия fs.Dir
который имеет текущие асинхронные операции.
ERR_DNS_SET_SERVERS_FAILED
¶
c-ares
не удалось установить DNS-сервер.
ERR_DOMAIN_CALLBACK_NOT_AVAILABLE
¶
В domain
модуль нельзя было использовать, так как он не мог установить требуемые перехватчики обработки ошибок, потому что process.setUncaughtExceptionCaptureCallback()
был вызван в более ранний момент времени.
ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE
¶
process.setUncaughtExceptionCaptureCallback()
нельзя было назвать, потому что domain
модуль был загружен раньше.
Трассировка стека расширяется, чтобы включить момент времени, в который domain
модуль был загружен.
ERR_ENCODING_INVALID_ENCODED_DATA
¶
Данные предоставлены TextDecoder()
API был недопустимым в соответствии с предоставленной кодировкой.
ERR_ENCODING_NOT_SUPPORTED
¶
Кодировка предоставлена TextDecoder()
API не был одним из WHATWG Поддерживаемые кодировки.
ERR_EVAL_ESM_CANNOT_PRINT
¶
--print
не может использоваться с входом ESM.
ERR_EVENT_RECURSION
¶
Вызывается, когда делается попытка рекурсивно отправить событие на EventTarget
.
ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE
¶
Контекст выполнения JS не связан со средой Node.js. Это может произойти, если Node.js используется в качестве встроенной библиотеки и некоторые хуки для движка JS не настроены должным образом.
ERR_FALSY_VALUE_REJECTION
¶
А Promise
это было выполнено обратным вызовом через util.callbackify()
был отклонен с ложным значением.
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM
¶
Используется, когда используется функция, недоступная для текущей платформы, на которой работает Node.js.
ERR_FS_CP_DIR_TO_NON_DIR
¶
Была сделана попытка скопировать каталог в не каталог (файл, символическую ссылку и т. Д.) С помощью fs.cp()
.
ERR_FS_CP_EEXIST
¶
Была сделана попытка скопировать файл, который уже существовал с fs.cp()
, с force
а также errorOnExist
установлен в true
.
ERR_FS_CP_EINVAL
¶
Когда используешь fs.cp()
, src
или dest
указал на недопустимый путь.
ERR_FS_CP_FIFO_PIPE
¶
Была сделана попытка скопировать именованный канал с fs.cp()
.
ERR_FS_CP_NON_DIR_TO_DIR
¶
Была сделана попытка скопировать не каталог (файл, символическую ссылку и т. Д.) В каталог с помощью fs.cp()
.
ERR_FS_CP_SOCKET
¶
Была сделана попытка скопировать в сокет с fs.cp()
.
ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY
¶
Когда используешь fs.cp()
, символическая ссылка в dest
указал на подкаталог src
.
ERR_FS_CP_UNKNOWN
¶
Была сделана попытка скопировать файл неизвестного типа с fs.cp()
.
ERR_FS_EISDIR
¶
Путь — это каталог.
ERR_FS_FILE_TOO_LARGE
¶
Была сделана попытка прочитать файл, размер которого превышает максимально допустимый размер для Buffer
.
ERR_FS_INVALID_SYMLINK_TYPE
¶
Недопустимый тип символической ссылки был передан в fs.symlink()
или fs.symlinkSync()
методы.
Была сделана попытка добавить дополнительные заголовки после того, как они уже были отправлены.
Указано недопустимое значение заголовка HTTP.
ERR_HTTP_INVALID_STATUS_CODE
¶
Код состояния находился за пределами обычного диапазона кодов состояния (100–999).
ERR_HTTP_REQUEST_TIMEOUT
¶
Клиент не отправил весь запрос в отведенное время.
ERR_HTTP_SOCKET_ENCODING
¶
Изменение кодировки сокета запрещено RFC 7230, раздел 3.
ERR_HTTP_TRAILER_INVALID
¶
В Trailer
заголовок был установлен, хотя кодировка передачи не поддерживает это.
ERR_HTTP2_ALTSVC_INVALID_ORIGIN
¶
Для фреймов HTTP / 2 ALTSVC требуется действительное происхождение.
ERR_HTTP2_ALTSVC_LENGTH
¶
Кадры HTTP / 2 ALTSVC ограничены максимум 16 382 байтами полезной нагрузки.
Для запросов HTTP / 2 с использованием CONNECT
метод, :authority
псевдозаголовок обязателен.
ERR_HTTP2_CONNECT_PATH
¶
Для запросов HTTP / 2 с использованием CONNECT
метод, :path
псевдозаголовок запрещен.
ERR_HTTP2_CONNECT_SCHEME
¶
Для запросов HTTP / 2 с использованием CONNECT
метод, :scheme
псевдозаголовок запрещен.
ERR_HTTP2_ERROR
¶
Произошла неспецифическая ошибка HTTP / 2.
ERR_HTTP2_GOAWAY_SESSION
¶
Новые потоки HTTP / 2 нельзя открывать после Http2Session
получил GOAWAY
кадр от подключенного однорангового узла.
Было предоставлено несколько значений для поля заголовка HTTP / 2, которое должно было иметь только одно значение.
Дополнительные заголовки были указаны после того, как был инициирован ответ HTTP / 2.
Была сделана попытка отправить несколько заголовков ответа.
ERR_HTTP2_INFO_STATUS_NOT_ALLOWED
¶
Информационные коды состояния HTTP (1xx
) не может быть установлен в качестве кода состояния ответа в ответах HTTP / 2.
Заголовки соединения HTTP / 1 запрещено использовать в запросах и ответах HTTP / 2.
Указано недопустимое значение заголовка HTTP / 2.
ERR_HTTP2_INVALID_INFO_STATUS
¶
Указан недопустимый информационный код состояния HTTP. Информационные коды состояния должны быть целыми числами между 100
а также 199
(включительно).
ERR_HTTP2_INVALID_ORIGIN
¶
HTTP / 2 ORIGIN
кадры требуют действительного происхождения.
ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH
¶
Вход Buffer
а также Uint8Array
экземпляры переданы в http2.getUnpackedSettings()
API должен иметь длину, кратную шести.
Только допустимые псевдозаголовки HTTP / 2 (:status
, :path
, :authority
, :scheme
, а также :method
) может быть использовано.
ERR_HTTP2_INVALID_SESSION
¶
Действие было выполнено с Http2Session
объект, который уже был уничтожен.
ERR_HTTP2_INVALID_SETTING_VALUE
¶
Для параметра HTTP / 2 указано недопустимое значение.
ERR_HTTP2_INVALID_STREAM
¶
Операция была выполнена над потоком, который уже был уничтожен.
ERR_HTTP2_MAX_PENDING_SETTINGS_ACK
¶
Всякий раз, когда HTTP / 2 SETTINGS
фрейм отправляется подключенному одноранговому узлу, одноранговый узел должен отправить подтверждение, что он получил и применил новый SETTINGS
. По умолчанию максимальное количество неподтвержденных SETTINGS
кадры могут быть отправлены в любой момент времени. Этот код ошибки используется при достижении этого предела.
ERR_HTTP2_NESTED_PUSH
¶
Была сделана попытка инициировать новый push-поток из push-потока. Вложенные push-потоки не разрешены.
ERR_HTTP2_NO_MEM
¶
Недостаточно памяти при использовании http2session.setLocalWindowSize(windowSize)
API.
ERR_HTTP2_NO_SOCKET_MANIPULATION
¶
Была предпринята попытка напрямую манипулировать (чтение, запись, пауза, возобновление и т. Д.) Сокетом, подключенным к Http2Session
.
ERR_HTTP2_ORIGIN_LENGTH
¶
HTTP / 2 ORIGIN
кадры ограничены длиной 16382 байта.
ERR_HTTP2_OUT_OF_STREAMS
¶
Количество потоков, созданных в одном сеансе HTTP / 2, достигло максимального предела.
ERR_HTTP2_PAYLOAD_FORBIDDEN
¶
Полезная нагрузка сообщения была указана для кода ответа HTTP, для которого полезная нагрузка запрещена.
ERR_HTTP2_PING_CANCEL
¶
Пинг HTTP / 2 был отменен.
ERR_HTTP2_PING_LENGTH
¶
Полезные данные ping HTTP / 2 должны иметь длину ровно 8 байтов.
Псевдозаголовок HTTP / 2 использован ненадлежащим образом. Псевдо-заголовки — это имена ключей заголовков, которые начинаются с :
приставка.
ERR_HTTP2_PUSH_DISABLED
¶
Была сделана попытка создать push-поток, который был отключен клиентом.
ERR_HTTP2_SEND_FILE
¶
Была сделана попытка использовать Http2Stream.prototype.responseWithFile()
API для отправки каталога.
ERR_HTTP2_SEND_FILE_NOSEEK
¶
Была сделана попытка использовать Http2Stream.prototype.responseWithFile()
API для отправки чего-то другого, кроме обычного файла, но offset
или length
были предоставлены варианты.
ERR_HTTP2_SESSION_ERROR
¶
В Http2Session
закрывается с ненулевым кодом ошибки.
ERR_HTTP2_SETTINGS_CANCEL
¶
В Http2Session
настройки отменены.
ERR_HTTP2_SOCKET_BOUND
¶
Была сделана попытка подключить Http2Session
возражать против net.Socket
или tls.TLSSocket
который уже был привязан к другому Http2Session
объект.
ERR_HTTP2_SOCKET_UNBOUND
¶
Была сделана попытка использовать socket
собственность Http2Session
это уже было закрыто.
ERR_HTTP2_STATUS_101
¶
Использование 101
Информационный код статуса запрещен в HTTP / 2.
ERR_HTTP2_STATUS_INVALID
¶
Указан недопустимый код состояния HTTP. Коды состояния должны быть целыми числами между 100
а также 599
(включительно).
ERR_HTTP2_STREAM_CANCEL
¶
An Http2Stream
был уничтожен до того, как какие-либо данные были переданы подключенному узлу.
ERR_HTTP2_STREAM_ERROR
¶
Ненулевой код ошибки был указан в RST_STREAM
Рамка.
ERR_HTTP2_STREAM_SELF_DEPENDENCY
¶
При установке приоритета для потока HTTP / 2 этот поток может быть помечен как зависимость для родительского потока. Этот код ошибки используется, когда делается попытка пометить поток и зависит от него самого.
ERR_HTTP2_TOO_MANY_INVALID_FRAMES
¶
Предел приемлемых недопустимых кадров протокола HTTP / 2, отправленных партнером, как указано в maxSessionInvalidFrames
вариант, был превышен.
ERR_HTTP2_TRAILERS_ALREADY_SENT
¶
Конечные заголовки уже отправлены на Http2Stream
.
ERR_HTTP2_TRAILERS_NOT_READY
¶
В http2stream.sendTrailers()
метод не может быть вызван до тех пор, пока 'wantTrailers'
событие испускается на Http2Stream
объект. В 'wantTrailers'
событие будет сгенерировано только в том случае, если waitForTrailers
опция установлена для Http2Stream
.
ERR_HTTP2_UNSUPPORTED_PROTOCOL
¶
http2.connect()
был передан URL-адрес, использующий любой протокол, кроме http:
или https:
.
ERR_ILLEGAL_CONSTRUCTOR
¶
Была предпринята попытка построить объект с использованием закрытого конструктора.
ERR_INCOMPATIBLE_OPTION_PAIR
¶
Пара опций несовместима друг с другом и не может использоваться одновременно.
ERR_INPUT_TYPE_NOT_ALLOWED
¶
Стабильность: 1 — экспериментальная
В --input-type
Флаг использовался для попытки выполнить файл. Этот флаг можно использовать только при вводе через --eval
, --print
или STDIN
.
ERR_INSPECTOR_ALREADY_ACTIVATED
¶
При использовании inspector
module была предпринята попытка активировать инспектор, когда он уже начал прослушивать порт. Использовать inspector.close()
прежде чем активировать его на другом адресе.
ERR_INSPECTOR_ALREADY_CONNECTED
¶
При использовании inspector
модуль, была предпринята попытка подключения, когда инспектор уже был подключен.
ERR_INSPECTOR_CLOSED
¶
При использовании inspector
модуля, была предпринята попытка использовать инспектор после того, как сессия уже закрылась.
ERR_INSPECTOR_COMMAND
¶
Произошла ошибка при подаче команды через inspector
модуль.
ERR_INSPECTOR_NOT_ACTIVE
¶
В inspector
не активен, когда inspector.waitForDebugger()
называется.
ERR_INSPECTOR_NOT_AVAILABLE
¶
В inspector
модуль недоступен для использования.
ERR_INSPECTOR_NOT_CONNECTED
¶
При использовании inspector
модуль, была предпринята попытка использовать инспектор до его подключения.
ERR_INSPECTOR_NOT_WORKER
¶
В основном потоке был вызван API, который можно использовать только из рабочего потока.
ERR_INTERNAL_ASSERTION
¶
Ошибка в Node.js или некорректное использование внутренних компонентов Node.js. Чтобы исправить ошибку, откройте проблему на https://github.com/nodejs/node/issues.
ERR_INVALID_ADDRESS_FAMILY
¶
Указанное семейство адресов не распознается API Node.js.
ERR_INVALID_ARG_TYPE
¶
В API Node.js был передан аргумент неправильного типа.
ERR_INVALID_ARG_VALUE
¶
Для данного аргумента было передано недопустимое или неподдерживаемое значение.
ERR_INVALID_ASYNC_ID
¶
Недействительный asyncId
или triggerAsyncId
был передан с использованием AsyncHooks
. Идентификатор меньше -1 никогда не должен происходить.
ERR_INVALID_BUFFER_SIZE
¶
Обмен был произведен на Buffer
но его размер был несовместим с операцией.
ERR_INVALID_CALLBACK
¶
Требовалась функция обратного вызова, но она не была предоставлена API Node.js.
ERR_INVALID_CHAR
¶
В заголовках обнаружены недопустимые символы.
ERR_INVALID_CURSOR_POS
¶
Курсор в данном потоке нельзя переместить в указанную строку без указанного столбца.
ERR_INVALID_FD
¶
Дескриптор файла (‘fd’) недействителен (например, имеет отрицательное значение).
ERR_INVALID_FD_TYPE
¶
Недопустимый тип дескриптора файла (‘fd’).
ERR_INVALID_FILE_URL_HOST
¶
API-интерфейс Node.js, который потребляет file:
URL-адреса (например, определенные функции в fs
module) обнаружил URL-адрес файла с несовместимым хостом. Эта ситуация может возникнуть только в Unix-подобных системах, где только localhost
или поддерживается пустой хост.
ERR_INVALID_FILE_URL_PATH
¶
API-интерфейс Node.js, который потребляет file:
URL-адреса (например, определенные функции в fs
module) обнаружил URL-адрес файла с несовместимым путем. Точная семантика для определения возможности использования пути зависит от платформы.
ERR_INVALID_HANDLE_TYPE
¶
Была сделана попытка отправить неподдерживаемый «дескриптор» по каналу связи IPC дочернему процессу. Видеть subprocess.send()
а также process.send()
для дополнительной информации.
ERR_INVALID_HTTP_TOKEN
¶
Предоставлен недопустимый токен HTTP.
ERR_INVALID_IP_ADDRESS
¶
IP-адрес недействителен.
ERR_INVALID_MODULE
¶
Была сделана попытка загрузить несуществующий или недействительный модуль.
ERR_INVALID_MODULE_SPECIFIER
¶
Строка импортированного модуля является недопустимым URL-адресом, именем пакета или указателем подпути пакета.
ERR_INVALID_PACKAGE_CONFIG
¶
Недействительный package.json
файл не прошел синтаксический анализ.
ERR_INVALID_PACKAGE_TARGET
¶
В package.json
"exports"
Поле содержит недопустимое значение сопоставления цели для попытки разрешения модуля.
ERR_INVALID_PERFORMANCE_MARK
¶
При использовании Performance Timing API (perf_hooks
), отметка о производительности недействительна.
ERR_INVALID_PROTOCOL
¶
Недействительный options.protocol
был передан http.request()
.
ERR_INVALID_REPL_EVAL_CONFIG
¶
Оба breakEvalOnSigint
а также eval
параметры были установлены в REPL
config, который не поддерживается.
ERR_INVALID_REPL_INPUT
¶
Вход не может использоваться в REPL
. Условия, при которых используется эта ошибка, описаны в REPL
документация.
ERR_INVALID_RETURN_PROPERTY
¶
Выбрасывается в случае, если параметр функции не предоставляет допустимое значение для одного из свойств возвращаемого объекта при выполнении.
ERR_INVALID_RETURN_PROPERTY_VALUE
¶
Выбрасывается в случае, если параметр функции не предоставляет тип ожидаемого значения для одного из свойств возвращаемого объекта при выполнении.
ERR_INVALID_RETURN_VALUE
¶
Вызывается в случае, если опция функции не возвращает ожидаемый тип значения при выполнении, например, когда ожидается, что функция вернет обещание.
ERR_INVALID_STATE
¶
Указывает, что операция не может быть завершена из-за недопустимого состояния. Например, объект может быть уже уничтожен или может выполнять другую операцию.
ERR_INVALID_SYNC_FORK_INPUT
¶
А Buffer
, TypedArray
, DataView
или string
был предоставлен как вход stdio для асинхронной вилки. См. Документацию по child_process
модуль для получения дополнительной информации.
ERR_INVALID_THIS
¶
Функция API Node.js была вызвана с несовместимым this
ценить.
const urlSearchParams = new URLSearchParams(
'foo=bar&baz=new'
);
const buf = Buffer.alloc(1);
urlSearchParams.has.call(buf, 'foo');
// Throws a TypeError with code 'ERR_INVALID_THIS'
ERR_INVALID_TRANSFER_OBJECT
¶
Недопустимый объект передачи был передан в postMessage()
.
ERR_INVALID_TUPLE
¶
Элемент в iterable
предоставлен WHATWG URLSearchParams
конструктор не представлял [name, value]
кортеж — то есть, если элемент не повторяется или не состоит ровно из двух элементов.
ERR_INVALID_URI
¶
Передан неверный URI.
ERR_INVALID_URL
¶
Недействительный URL был передан в WHATWG URL
конструктор или наследие url.parse()
быть разобранным. Выброшенный объект ошибки обычно имеет дополнительное свойство 'input'
который содержит URL-адрес, который не удалось проанализировать.
ERR_INVALID_URL_SCHEME
¶
Была сделана попытка использовать URL несовместимой схемы (протокола) для определенной цели. Он используется только в WHATWG URL API поддержка в fs
модуль (который принимает только URL-адреса с 'file'
схема), но может использоваться и в других API Node.js в будущем.
ERR_IPC_CHANNEL_CLOSED
¶
Была сделана попытка использовать канал связи IPC, который уже был закрыт.
ERR_IPC_DISCONNECTED
¶
Была сделана попытка отключить уже отключенный канал связи IPC. См. Документацию по child_process
модуль для получения дополнительной информации.
ERR_IPC_ONE_PIPE
¶
Была предпринята попытка создать дочерний процесс Node.js, использующий более одного канала связи IPC. См. Документацию по child_process
модуль для получения дополнительной информации.
ERR_IPC_SYNC_FORK
¶
Была предпринята попытка открыть канал связи IPC с помощью синхронно разветвленного процесса Node.js. См. Документацию по child_process
модуль для получения дополнительной информации.
ERR_MANIFEST_ASSERT_INTEGRITY
¶
Была предпринята попытка загрузить ресурс, но ресурс не соответствовал целостности, определенной в манифесте политики. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_DEPENDENCY_MISSING
¶
Была предпринята попытка загрузить ресурс, но ресурс не был указан как зависимость от расположения, в котором его пытались загрузить. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INTEGRITY_MISMATCH
¶
Была сделана попытка загрузить манифест политики, но в манифесте было несколько записей для ресурса, которые не совпадали друг с другом. Обновите записи манифеста, чтобы они соответствовали, чтобы устранить эту ошибку. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INVALID_RESOURCE_FIELD
¶
Ресурс манифеста политики имел недопустимое значение для одного из полей. Обновите запись манифеста, чтобы она соответствовала, чтобы устранить эту ошибку. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INVALID_SPECIFIER
¶
Ресурс манифеста политики имел недопустимое значение для одного из сопоставлений зависимостей. Обновите запись манифеста, чтобы она соответствовала разрешению этой ошибки. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_PARSE_POLICY
¶
Была предпринята попытка загрузить манифест политики, но не удалось проанализировать манифест. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_TDZ
¶
Была предпринята попытка чтения из манифеста политики, но инициализация манифеста еще не произошла. Вероятно, это ошибка в Node.js.
ERR_MANIFEST_UNKNOWN_ONERROR
¶
Манифест политики был загружен, но для его поведения «onerror» было неизвестно значение. Документацию для политика манифесты для получения дополнительной информации.
ERR_MEMORY_ALLOCATION_FAILED
¶
Была предпринята попытка выделить память (обычно на уровне C ++), но она не удалась.
ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE
¶
Сообщение отправлено MessagePort
не удалось десериализовать в целевой vm Context
. Не все объекты Node.js могут быть успешно созданы в любом контексте в настоящее время, и попытки передать их с помощью postMessage()
в этом случае может выйти из строя принимающая сторона.
ERR_METHOD_NOT_IMPLEMENTED
¶
Метод требуется, но не реализован.
ERR_MISSING_ARGS
¶
Не был передан обязательный аргумент API Node.js. Это используется только для строгого соответствия спецификации API (которая в некоторых случаях может принимать func(undefined)
но нет func()
). В большинстве собственных API-интерфейсов Node.js func(undefined)
а также func()
рассматриваются одинаково, а ERR_INVALID_ARG_TYPE
вместо этого можно использовать код ошибки.
ERR_MISSING_OPTION
¶
Для API-интерфейсов, которые принимают объекты параметров, некоторые параметры могут быть обязательными. Этот код выдается, если отсутствует необходимая опция.
ERR_MISSING_PASSPHRASE
¶
Была сделана попытка прочитать зашифрованный ключ без указания ключевой фразы.
ERR_MISSING_PLATFORM_FOR_WORKER
¶
Платформа V8, используемая этим экземпляром Node.js, не поддерживает создание рабочих. Это вызвано отсутствием поддержки Embedder для Workers. В частности, эта ошибка не возникает при использовании стандартных сборок Node.js.
ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST
¶
Объект, который должен быть явно указан в transferList
аргумент находится в объекте, переданном в postMessage()
звоните, но не указано в transferList
для этого звонка. Обычно это MessagePort
.
В версиях Node.js до v15.0.0 использованный здесь код ошибки был ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST
. Однако набор переносимых типов объектов был расширен, чтобы охватить больше типов, чем MessagePort
.
ERR_MODULE_NOT_FOUND
¶
Стабильность: 1 — экспериментальная
An Модуль ES не может быть решен.
ERR_MULTIPLE_CALLBACK
¶
Обратный звонок был вызван более одного раза.
Обратный вызов почти всегда предназначен для однократного вызова, поскольку запрос может быть выполнен или отклонен, но не оба одновременно. Последнее станет возможным, если вызвать обратный вызов более одного раза.
ERR_NAPI_CONS_FUNCTION
¶
При использовании Node-API
, переданный конструктор не является функцией.
ERR_NAPI_INVALID_DATAVIEW_ARGS
¶
Во время звонка napi_create_dataview()
, данный offset
находился за пределами окна просмотра данных или offset + length
был больше, чем длина заданного buffer
.
ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT
¶
Во время звонка napi_create_typedarray()
предоставленные offset
не был кратен размеру элемента.
ERR_NAPI_INVALID_TYPEDARRAY_LENGTH
¶
Во время звонка napi_create_typedarray()
, (length * size_of_element) + byte_offset
был больше, чем длина заданного buffer
.
ERR_NAPI_TSFN_CALL_JS
¶
Произошла ошибка при вызове части JavaScript поточно-ориентированной функции.
ERR_NAPI_TSFN_GET_UNDEFINED
¶
Произошла ошибка при попытке получить код JavaScript. undefined
ценить.
ERR_NAPI_TSFN_START_IDLE_LOOP
¶
В основном потоке значения удаляются из очереди, связанной с поточно-ориентированной функцией, в цикле ожидания. Эта ошибка указывает на то, что произошла ошибка при попытке запустить цикл.
ERR_NAPI_TSFN_STOP_IDLE_LOOP
¶
Если в очереди больше не осталось элементов, цикл простоя должен быть приостановлен. Эта ошибка указывает на то, что не удалось остановить цикл холостого хода.
ERR_NO_CRYPTO
¶
Была предпринята попытка использовать функции шифрования, пока Node.js не был скомпилирован с поддержкой шифрования OpenSSL.
ERR_NO_ICU
¶
Была предпринята попытка использовать функции, требующие ICU, но Node.js не был скомпилирован с поддержкой ICU.
ERR_NON_CONTEXT_AWARE_DISABLED
¶
Родной аддон, не зависящий от контекста, был загружен в процессе, который их запрещает.
ERR_OUT_OF_RANGE
¶
Заданное значение выходит за пределы допустимого диапазона.
ERR_PACKAGE_IMPORT_NOT_DEFINED
¶
В package.json
"imports"
поле не определяет заданное отображение спецификатора внутреннего пакета.
ERR_PACKAGE_PATH_NOT_EXPORTED
¶
В package.json
"exports"
не экспортирует запрошенный подпуть. Поскольку экспорт инкапсулирован, частные внутренние модули, которые не экспортируются, не могут быть импортированы через разрешение пакета, если не используется абсолютный URL-адрес.
ERR_PERFORMANCE_INVALID_TIMESTAMP
¶
Для отметки производительности или показателя было предоставлено недопустимое значение метки времени.
ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS
¶
Предусмотрены недопустимые варианты измерения производительности.
ERR_PROTO_ACCESS
¶
Доступ Object.prototype.__proto__
было запрещено использовать --disable-proto=throw
. Object.getPrototypeOf
а также Object.setPrototypeOf
следует использовать для получения и установки прототипа объекта.
ERR_REQUIRE_ESM
¶
Стабильность: 1 — экспериментальная
Была сделана попытка require()
ан Модуль ES.
ERR_SCRIPT_EXECUTION_INTERRUPTED
¶
Выполнение скрипта было прервано SIGINT
(Например, Ctrl+C был нажат.)
ERR_SCRIPT_EXECUTION_TIMEOUT
¶
Истекло время выполнения сценария, возможно, из-за ошибок в выполняемом сценарии.
ERR_SERVER_ALREADY_LISTEN
¶
В server.listen()
метод был вызван в то время как net.Server
уже слушал. Это относится ко всем экземплярам net.Server
, включая HTTP, HTTPS и HTTP / 2 Server
экземпляры.
ERR_SERVER_NOT_RUNNING
¶
В server.close()
метод был вызван, когда net.Server
не работал. Это относится ко всем экземплярам net.Server
, включая HTTP, HTTPS и HTTP / 2 Server
экземпляры.
ERR_SOCKET_ALREADY_BOUND
¶
Была сделана попытка привязать уже связанный сокет.
ERR_SOCKET_BAD_BUFFER_SIZE
¶
Был передан недопустимый (отрицательный) размер для recvBufferSize
или sendBufferSize
варианты в dgram.createSocket()
.
ERR_SOCKET_BAD_PORT
¶
Функция API, ожидающая порта> = 0 и <65536, получила недопустимое значение.
ERR_SOCKET_BAD_TYPE
¶
Функция API, ожидающая типа сокета (udp4
или udp6
) получил недопустимое значение.
ERR_SOCKET_BUFFER_SIZE
¶
При использовании dgram.createSocket()
, размер получения или отправки Buffer
не может быть определено.
ERR_SOCKET_CLOSED
¶
Была сделана попытка работать с уже закрытым сокетом.
ERR_SOCKET_DGRAM_IS_CONNECTED
¶
А dgram.connect()
вызов был сделан на уже подключенном сокете.
ERR_SOCKET_DGRAM_NOT_CONNECTED
¶
А dgram.disconnect()
или dgram.remoteAddress()
звонок был сделан на отключенной розетке.
ERR_SOCKET_DGRAM_NOT_RUNNING
¶
Был сделан вызов, но подсистема UDP не работала.
ERR_SRI_PARSE
¶
Строка была предоставлена для проверки целостности подресурса, но не может быть проанализирована. Проверьте формат атрибутов целостности, посмотрев на Спецификация целостности подресурсов.
ERR_STREAM_ALREADY_FINISHED
¶
Был вызван метод потока, который не может быть завершен, поскольку поток был завершен.
ERR_STREAM_CANNOT_PIPE
¶
Была сделана попытка позвонить stream.pipe()
на Writable
транслировать.
ERR_STREAM_DESTROYED
¶
Был вызван метод потока, который не может быть завершен, поскольку поток был уничтожен с использованием stream.destroy()
.
ERR_STREAM_NULL_VALUES
¶
Была сделана попытка позвонить stream.write()
с null
кусок.
ERR_STREAM_PREMATURE_CLOSE
¶
Ошибка, возвращенная stream.finished()
а также stream.pipeline()
, когда поток или конвейер завершаются некорректно, без явной ошибки.
ERR_STREAM_PUSH_AFTER_EOF
¶
Была сделана попытка позвонить stream.push()
после null
(EOF) был отправлен в поток.
ERR_STREAM_UNSHIFT_AFTER_END_EVENT
¶
Была сделана попытка позвонить stream.unshift()
после 'end'
событие было отправлено.
ERR_STREAM_WRAP
¶
Предотвращает прерывание, если строковый декодер был установлен на Socket или если декодер находится в objectMode
.
const Socket = require('net').Socket;
const instance = new Socket();
instance.setEncoding('utf8');
ERR_STREAM_WRITE_AFTER_END
¶
Была сделана попытка позвонить stream.write()
после stream.end()
был вызван.
ERR_STRING_TOO_LONG
¶
Была сделана попытка создать строку длиннее максимально допустимой.
ERR_SYNTHETIC
¶
Искусственный объект ошибки, используемый для захвата стека вызовов для диагностических отчетов.
ERR_SYSTEM_ERROR
¶
В процессе Node.js произошла неопределенная или неспецифическая системная ошибка. Объект ошибки будет иметь err.info
свойство объекта с дополнительной информацией.
ERR_TLS_CERT_ALTNAME_INVALID
¶
При использовании TLS имя хоста / IP-адрес однорангового узла не соответствует ни одному из subjectAltNames
в его сертификате.
ERR_TLS_DH_PARAM_SIZE
¶
При использовании TLS параметр, предлагаемый для алгоритма Диффи-Хеллмана (DH
) протокол согласования ключей слишком мал. По умолчанию длина ключа должна быть больше или равна 1024 битам, чтобы избежать уязвимостей, хотя настоятельно рекомендуется использовать 2048 бит или больше для большей безопасности.
ERR_TLS_HANDSHAKE_TIMEOUT
¶
Время ожидания подтверждения TLS / SSL истекло. В этом случае сервер также должен прервать соединение.
ERR_TLS_INVALID_CONTEXT
¶
Контекст должен быть SecureContext
.
ERR_TLS_INVALID_PROTOCOL_METHOD
¶
Указанный secureProtocol
метод недействителен. Он либо неизвестен, либо отключен, потому что небезопасен.
ERR_TLS_INVALID_PROTOCOL_VERSION
¶
Допустимые версии протокола TLS: 'TLSv1'
, 'TLSv1.1'
, или 'TLSv1.2'
.
ERR_TLS_INVALID_STATE
¶
Сокет TLS должен быть подключен и надежно установлен. Перед продолжением убедитесь, что «безопасное» событие запущено.
ERR_TLS_PROTOCOL_VERSION_CONFLICT
¶
Попытка установить протокол TLS minVersion
или maxVersion
конфликтует с попыткой установить secureProtocol
явно. Используйте тот или иной механизм.
ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED
¶
Не удалось установить подсказку идентификатора PSK. Подсказка может быть слишком длинной.
ERR_TLS_RENEGOTIATION_DISABLED
¶
Была сделана попытка повторно согласовать TLS на экземпляре сокета с отключенным TLS.
ERR_TLS_REQUIRED_SERVER_NAME
¶
При использовании TLS server.addContext()
был вызван без указания имени хоста в первом параметре.
ERR_TLS_SESSION_ATTACK
¶
Обнаружено чрезмерное количество повторных согласований TLS, что является потенциальным вектором атак типа «отказ в обслуживании».
ERR_TLS_SNI_FROM_SERVER
¶
Была предпринята попытка выдать указание имени сервера из сокета на стороне сервера TLS, который действителен только для клиента.
ERR_TRACE_EVENTS_CATEGORY_REQUIRED
¶
В trace_events.createTracing()
требуется по крайней мере одна категория событий трассировки.
ERR_TRACE_EVENTS_UNAVAILABLE
¶
В trace_events
модуль не может быть загружен, потому что Node.js был скомпилирован с --without-v8-platform
флаг.
ERR_TRANSFORM_ALREADY_TRANSFORMING
¶
А Transform
поток завершился, пока он все еще преобразовывался.
ERR_TRANSFORM_WITH_LENGTH_0
¶
А Transform
поток закончился с данными, все еще находящимися в буфере записи.
ERR_TTY_INIT_FAILED
¶
Инициализация TTY не удалась из-за системной ошибки.
ERR_UNAVAILABLE_DURING_EXIT
¶
Функция была вызвана в process.on('exit')
обработчик, который не должен вызываться внутри process.on('exit')
обработчик.
ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET
¶
process.setUncaughtExceptionCaptureCallback()
был вызван дважды, без предварительного сброса обратного вызова на null
.
Эта ошибка предназначена для предотвращения случайной перезаписи обратного вызова, зарегистрированного из другого модуля.
ERR_UNESCAPED_CHARACTERS
¶
Получена строка, содержащая неэкранированные символы.
ERR_UNHANDLED_ERROR
¶
Произошла необработанная ошибка (например, когда 'error'
событие испускается EventEmitter
но 'error'
обработчик не зарегистрирован).
ERR_UNKNOWN_BUILTIN_MODULE
¶
Используется для определения определенного вида внутренней ошибки Node.js, которая обычно не должна запускаться кодом пользователя. Экземпляры этой ошибки указывают на внутреннюю ошибку в самом двоичном файле Node.js.
ERR_UNKNOWN_CREDENTIAL
¶
Был передан несуществующий идентификатор группы или пользователя Unix.
ERR_UNKNOWN_ENCODING
¶
В API передан неверный или неизвестный параметр кодировки.
ERR_UNKNOWN_FILE_EXTENSION
¶
Стабильность: 1 — экспериментальная
Была сделана попытка загрузить модуль с неизвестным или неподдерживаемым расширением файла.
ERR_UNKNOWN_MODULE_FORMAT
¶
Стабильность: 1 — экспериментальная
Была сделана попытка загрузить модуль с неизвестным или неподдерживаемым форматом.
ERR_UNKNOWN_SIGNAL
¶
Неверный или неизвестный сигнал процесса был передан API, ожидающему действительного сигнала (например, subprocess.kill()
).
ERR_UNSUPPORTED_DIR_IMPORT
¶
import
URL-адрес каталога не поддерживается. Вместо, Самостоятельная ссылка на пакет, используя его имя а также определить настраиваемый подпуть в "exports"
поле package.json
файл.
import './'; // unsupported
import './index.js'; // supported
import 'package-name'; // supported
ERR_UNSUPPORTED_ESM_URL_SCHEME
¶
import
со схемами URL, отличными от file
а также data
не поддерживается.
ERR_VALID_PERFORMANCE_ENTRY_TYPE
¶
При использовании Performance Timing API (perf_hooks
) допустимые типы записей производительности не найдены.
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
¶
Обратный вызов динамического импорта не указан.
ERR_VM_MODULE_ALREADY_LINKED
¶
Модуль, который пытались связать, не подходит для связывания по одной из следующих причин:
- Он уже был связан (
linkingStatus
является'linked'
) - Это связано (
linkingStatus
является'linking'
) - Не удалось установить связь для этого модуля (
linkingStatus
является'errored'
)
ERR_VM_MODULE_CACHED_DATA_REJECTED
¶
В cachedData
Параметр, переданный конструктору модуля, недопустим.
ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA
¶
Кэшированные данные не могут быть созданы для модулей, которые уже были оценены.
ERR_VM_MODULE_DIFFERENT_CONTEXT
¶
Модуль, возвращаемый функцией компоновщика, находится в другом контексте, чем родительский модуль. Связанные модули должны иметь общий контекст.
ERR_VM_MODULE_LINKING_ERRORED
¶
Функция компоновщика вернула модуль, для которого не удалось выполнить связывание.
ERR_VM_MODULE_LINK_FAILURE
¶
Модуль не удалось связать из-за сбоя.
ERR_VM_MODULE_NOT_MODULE
¶
Выполненное значение обещания связывания не является vm.Module
объект.
ERR_VM_MODULE_STATUS
¶
Текущий статус модуля не позволяет выполнить эту операцию. Конкретный смысл ошибки зависит от конкретной функции.
ERR_WASI_ALREADY_STARTED
¶
Экземпляр WASI уже запущен.
ERR_WASI_NOT_STARTED
¶
Экземпляр WASI не запущен.
ERR_WORKER_INIT_FAILED
¶
В Worker
Ошибка инициализации.
ERR_WORKER_INVALID_EXEC_ARGV
¶
В execArgv
вариант передан в Worker
конструктор содержит недопустимые флаги.
ERR_WORKER_NOT_RUNNING
¶
Операция завершилась неудачно, потому что Worker
экземпляр в настоящее время не запущен.
ERR_WORKER_OUT_OF_MEMORY
¶
В Worker
Экземпляр остановлен, поскольку достиг предела памяти.
ERR_WORKER_PATH
¶
Путь для основного скрипта рабочего не является ни абсолютным, ни относительным путем, начинающимся с ./
или ../
.
ERR_WORKER_UNSERIALIZABLE_ERROR
¶
Все попытки сериализации неперехваченного исключения из рабочего потока завершились неудачно.
ERR_WORKER_UNSUPPORTED_OPERATION
¶
Запрошенная функциональность не поддерживается в рабочих потоках.
ERR_ZLIB_INITIALIZATION_FAILED
¶
Создание zlib
сбой объекта из-за неправильной конфигурации.
Получено слишком много данных заголовка HTTP. Для защиты от злонамеренных или неправильно настроенных клиентов, если получено более 8 КБ данных HTTP-заголовка, анализ HTTP будет прерван без создания объекта запроса или ответа, и Error
с этим кодом будет выпущен.
HPE_UNEXPECTED_CONTENT_LENGTH
¶
Сервер отправляет как Content-Length
заголовок и Transfer-Encoding: chunked
.
Transfer-Encoding: chunked
позволяет серверу поддерживать постоянное соединение HTTP для динамически генерируемого контента. В этом случае Content-Length
Заголовок HTTP использовать нельзя.
Использовать Content-Length
или Transfer-Encoding: chunked
.
MODULE_NOT_FOUND
¶
Не удалось разрешить файл модуля при попытке require()
или import
операция.
Устаревшие коды ошибок Node.js¶
Стабильность: 0 — Не рекомендуется. Эти коды ошибок либо несовместимы, либо были удалены.
ERR_CANNOT_TRANSFER_OBJECT
¶
Значение, переданное в postMessage()
содержит объект, который не поддерживается для передачи.
ERR_CRYPTO_HASH_DIGEST_NO_UTF16
¶
Кодировка UTF-16 использовалась с hash.digest()
. В то время как hash.digest()
метод позволяет encoding
аргумент, который должен быть передан, в результате чего метод возвращает строку, а не Buffer
, кодировка UTF-16 (например, ucs
или utf16le
) не поддерживается.
ERR_HTTP2_FRAME_ERROR
¶
Используется при сбое отправки отдельного кадра в сеансе HTTP / 2.
Используется, когда ожидается объект заголовков HTTP / 2.
Используется, когда в сообщении HTTP / 2 отсутствует требуемый заголовок.
Информационные заголовки HTTP / 2 должны отправляться только прежний позвонить в Http2Stream.prototype.respond()
метод.
ERR_HTTP2_STREAM_CLOSED
¶
Используется, когда действие было выполнено над уже закрытым потоком HTTP / 2.
ERR_HTTP_INVALID_CHAR
¶
Используется, когда в сообщении статуса ответа HTTP (фраза причины) обнаружен недопустимый символ.
ERR_INDEX_OUT_OF_RANGE
¶
Данный индекс был вне допустимого диапазона (например, отрицательные смещения).
ERR_INVALID_OPT_VALUE
¶
В объект опций было передано недопустимое или неожиданное значение.
ERR_INVALID_OPT_VALUE_ENCODING
¶
Передана неверная или неизвестная кодировка файла.
ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST
¶
Этот код ошибки был заменен на ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST
в Node.js v15.0.0, потому что он больше не точен, поскольку теперь существуют и другие типы переносимых объектов.
ERR_NAPI_CONS_PROTOTYPE_OBJECT
¶
Используется Node-API
когда Constructor.prototype
не объект.
ERR_NO_LONGER_SUPPORTED
¶
API Node.js был вызван неподдерживаемым способом, например Buffer.write(string, encoding, offset[, length])
.
ERR_OPERATION_FAILED
¶
Не удалось выполнить операцию. Обычно это используется, чтобы сигнализировать об общем сбое асинхронной операции.
ERR_OUTOFMEMORY
¶
Обычно используется для определения того, что операция вызвала нехватку памяти.
ERR_PARSE_HISTORY_DATA
¶
В repl
модулю не удалось проанализировать данные из файла истории REPL.
ERR_SOCKET_CANNOT_SEND
¶
Данные не могут быть отправлены через сокет.
ERR_STDERR_CLOSE
¶
Была сделана попытка закрыть process.stderr
транслировать. По замыслу Node.js не позволяет stdout
или stderr
потоки должны быть закрыты кодом пользователя.
ERR_STDOUT_CLOSE
¶
Была сделана попытка закрыть process.stdout
транслировать. По замыслу Node.js не позволяет stdout
или stderr
потоки должны быть закрыты кодом пользователя.
ERR_STREAM_READ_NOT_IMPLEMENTED
¶
Используется, когда делается попытка использовать читаемый поток, который не реализован readable._read()
.
ERR_TLS_RENEGOTIATION_FAILED
¶
Используется, когда запрос на повторное согласование TLS завершился ошибкой неспецифическим образом.
ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER
¶
А SharedArrayBuffer
чья память не управляется механизмом JavaScript или Node.js. во время сериализации. Такой SharedArrayBuffer
не может быть сериализован.
Это может произойти только тогда, когда нативные аддоны создают SharedArrayBuffer
s в «внешнем» режиме или поместите существующий SharedArrayBuffer
во внешний режим.
ERR_UNKNOWN_STDIN_TYPE
¶
Была предпринята попытка запустить процесс Node.js с неизвестным stdin
тип файла. Эта ошибка обычно указывает на ошибку в самом Node.js, хотя пользовательский код может вызвать ее.
ERR_UNKNOWN_STREAM_TYPE
¶
Была предпринята попытка запустить процесс Node.js с неизвестным stdout
или stderr
тип файла. Эта ошибка обычно указывает на ошибку в самом Node.js, хотя пользовательский код может вызвать ее.
ERR_V8BREAKITERATOR
¶
V8 BreakIterator
API использовался, но не установлен полный набор данных ICU.
ERR_VALUE_OUT_OF_RANGE
¶
Используется, когда заданное значение выходит за пределы допустимого диапазона.
ERR_VM_MODULE_NOT_LINKED
¶
Перед созданием экземпляра модуль должен быть успешно связан.
ERR_WORKER_UNSUPPORTED_EXTENSION
¶
Имя пути, используемое для основного сценария рабочего, имеет неизвестное расширение файла.
ERR_ZLIB_BINDING_CLOSED
¶
Используется, когда делается попытка использовать zlib
объект после того, как он уже был закрыт.
ERR_CPU_USAGE
¶
Родной звонок от process.cpuUsage
не может быть обработано.
Show / Hide Table of Contents
Represents arguments for a ContextMenuErrored
Inheritance
Object
ContextMenuErrorEventArgs
Namespace: DSharpPlus.SlashCommands.EventArgs
Assembly: cs.temp.dll.dll
Syntax
public class ContextMenuErrorEventArgs : AsyncEventArgs
Properties
Context
The context of the command.
Declaration
public ContextMenuContext Context { get; }
Property Value
Type | Description |
---|---|
ContextMenuContext |
Exception
The exception thrown.
Declaration
public Exception Exception { get; }
Property Value
Type | Description |
---|---|
Exception |
The following section outlines the API of discord.py.
Note
This module uses the Python logging module to log diagnostic and errors
in an output independent way. If the logging module is not configured,
these logs will not be output anywhere. See Setting Up Logging for
more information on how to set up and use the logging module with
discord.py.
Client¶
-
class
discord.
Client
(*, loop=None, **options)¶ -
Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.A number of options can be passed to the
Client
.Parameters: - max_messages (Optional[int]) – The maximum number of messages to store in
messages
.
This defaults to 5000. Passing in None or a value less than 100
will use the default instead of the passed in value. - loop (Optional[event loop]) – The event loop to use for asynchronous operations. Defaults to
None
,
in which case the default event loop is used viaasyncio.get_event_loop()
. - cache_auth (Optional[bool]) – Indicates if
login()
should cache the authentication tokens. Defaults
toTrue
. The method in which the cache is written is done by writing to
disk to a temporary directory. - connector (aiohttp.BaseConnector) – The connector to use for connection pooling. Useful for proxies, e.g.
with a ProxyConnector. - shard_id (Optional[int]) – Integer starting at 0 and less than shard_count.
- shard_count (Optional[int]) – The total number of shards.
-
user
¶ -
Optional[
User
] – Represents the connected client. None if not logged in.
-
voice_clients
¶ -
iterable of
VoiceClient
– Represents a list of voice connections. To connect to voice use
join_voice_channel()
. To query the voice connection state use
is_voice_connected()
.
-
servers
¶ -
iterable of
Server
– The servers that the connected client is a member of.
-
private_channels
¶ -
iterable of
PrivateChannel
– The private channels that the connected client is participating on.
-
messages
¶ -
A deque of
Message
that the client has received from all
servers and private messages. The number of messages stored in this
deque is controlled by themax_messages
parameter.
-
email
¶ -
The email used to login. This is only set if login is successful,
otherwise it’s None.
-
ws
¶ -
The websocket gateway the client is currently connected to. Could be None.
-
loop
¶ -
The event loop that the client uses for HTTP requests and websocket operations.
-
on_error
(event_method, *args, **kwargs)¶ -
This function is a coroutine.
The default error handler provided by the client.
By default this prints to
sys.stderr
however it could be
overridden to have a different implementation.
Checkdiscord.on_error()
for more details.
-
login
(*args, **kwargs)¶ -
This function is a coroutine.
Logs in the client with the specified credentials.
This function can be used in two different ways.
await client.login('token') # or await client.login('email', 'password')
More than 2 parameters or less than 1 parameter raises a
TypeError
.Parameters: bot (bool) – Keyword argument that specifies if the account logging on is a bot
token or not. Only useful for logging in with a static token.
Ignored for the email and password combo. Defaults toTrue
.Raises: LoginFailure
– The wrong credentials are passed.HTTPException
– An unknown HTTP related error occurred,
usually when it isn’t 200 or the known incorrect credentials
passing status code.TypeError
– The incorrect number of parameters is passed.
-
logout
()¶ -
This function is a coroutine.
Logs out of Discord and closes all connections.
-
connect
()¶ -
This function is a coroutine.
Creates a websocket connection and lets the websocket listen
to messages from discord.Raises: GatewayNotFound
– If the gateway to connect to discord is not found. Usually if this
is thrown then there is a discord API outage.ConnectionClosed
– The websocket connection has been terminated.
-
close
()¶ -
This function is a coroutine.
Closes the connection to discord.
-
start
(*args, **kwargs)¶ -
This function is a coroutine.
A shorthand coroutine for
login()
+connect()
.
-
run
(*args, **kwargs)¶ -
A blocking call that abstracts away the event loop
initialisation from you.If you want more control over the event loop then this
function should not be used. Usestart()
coroutine
orconnect()
+login()
.Roughly Equivalent to:
try: loop.run_until_complete(start(*args, **kwargs)) except KeyboardInterrupt: loop.run_until_complete(logout()) # cancel all tasks lingering finally: loop.close()
Warning
This function must be the last function to call due to the fact that it
is blocking. That means that registration of events or anything being
called after this function call will not execute until it returns.
-
is_logged_in
¶ -
bool – Indicates if the client has logged in successfully.
-
is_closed
¶ -
bool – Indicates if the websocket connection is closed.
-
get_channel
(id)¶ -
Returns a
Channel
orPrivateChannel
with the following ID. If not found, returns None.
-
get_server
(id)¶ -
Returns a
Server
with the given ID. If not found, returns None.
-
get_all_emojis
()¶ -
Returns a generator with every
Emoji
the client can see.
-
get_all_channels
()¶ -
A generator that retrieves every
Channel
the client can ‘access’.This is equivalent to:
for server in client.servers: for channel in server.channels: yield channel
Note
Just because you receive a
Channel
does not mean that
you can communicate in said channel.Channel.permissions_for()
should
be used for that.
-
get_all_members
()¶ -
Returns a generator with every
Member
the client can see.This is equivalent to:
for server in client.servers: for member in server.members: yield member
-
wait_until_ready
()¶ -
This function is a coroutine.
This coroutine waits until the client is all ready. This could be considered
another way of asking fordiscord.on_ready()
except meant for your own
background tasks.
-
wait_until_login
()¶ -
This function is a coroutine.
This coroutine waits until the client is logged on successfully. This
is different from waiting until the client’s state is all ready. For
that checkdiscord.on_ready()
andwait_until_ready()
.
-
wait_for_message
(timeout=None, *, author=None, channel=None, content=None, check=None)¶ -
This function is a coroutine.
Waits for a message reply from Discord. This could be seen as another
discord.on_message()
event outside of the actual event. This could
also be used for follow-ups and easier user interactions.The keyword arguments passed into this function are combined using the logical and
operator. Thecheck
keyword argument can be used to pass in more complicated
checks and must be a regular function (not a coroutine).The
timeout
parameter is passed into asyncio.wait_for. By default, it
does not timeout. Instead of throwingasyncio.TimeoutError
the coroutine
catches the exception and returnsNone
instead of aMessage
.If the
check
predicate throws an exception, then the exception is propagated.This function returns the first message that meets the requirements.
Examples
Basic example:
@client.event async def on_message(message): if message.content.startswith('$greet'): await client.send_message(message.channel, 'Say hello') msg = await client.wait_for_message(author=message.author, content='hello') await client.send_message(message.channel, 'Hello.')
Asking for a follow-up question:
@client.event async def on_message(message): if message.content.startswith('$start'): await client.send_message(message.channel, 'Type $stop 4 times.') for i in range(4): msg = await client.wait_for_message(author=message.author, content='$stop') fmt = '{} left to go...' await client.send_message(message.channel, fmt.format(3 - i)) await client.send_message(message.channel, 'Good job!')
Advanced filters using
check
:@client.event async def on_message(message): if message.content.startswith('$cool'): await client.send_message(message.channel, 'Who is cool? Type $name namehere') def check(msg): return msg.content.startswith('$name') message = await client.wait_for_message(author=message.author, check=check) name = message.content[len('$name'):].strip() await client.send_message(message.channel, '{} is cool indeed'.format(name))
Parameters: - timeout (float) – The number of seconds to wait before returning
None
. - author (
Member
orUser
) – The author the message must be from. - channel (
Channel
orPrivateChannel
orObject
) – The channel the message must be from. - content (str) – The exact content the message must have.
- check (function) – A predicate for other complicated checks. The predicate must take
aMessage
as its only parameter.
Returns: The message that you requested for.
Return type: Message
- timeout (float) – The number of seconds to wait before returning
-
wait_for_reaction
(emoji=None, *, user=None, timeout=None, message=None, check=None)¶ -
This function is a coroutine.
Waits for a message reaction from Discord. This is similar to
wait_for_message()
and could be seen as anotheron_reaction_add()
event outside of the actual event.
This could be used for follow up situations.Similar to
wait_for_message()
, the keyword arguments are combined using logical
AND operator. Thecheck
keyword argument can be used to pass in more complicated
checks and must a regular function taking in two arguments,(reaction, user)
. It
must not be a coroutine.The
timeout
parameter is passed into asyncio.wait_for. By default, it
does not timeout. Instead of throwingasyncio.TimeoutError
the coroutine
catches the exception and returnsNone
instead of a the(reaction, user)
tuple.If the
check
predicate throws an exception, then the exception is propagated.The
emoji
parameter can be either aEmoji
, astr
representing
an emoji, or a sequence of either type. If theemoji
parameter is a sequence
then the first reaction emoji that is in the list is returned. IfNone
is
passed then the first reaction emoji used is returned.This function returns the first reaction that meets the requirements.
Examples
Basic Example:
@client.event async def on_message(message): if message.content.startswith('$react'): msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.') res = await client.wait_for_reaction(['👍', '👎'], message=msg) await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
Checking for reaction emoji regardless of skin tone:
@client.event async def on_message(message): if message.content.startswith('$react'): msg = await client.send_message(message.channel, 'React with thumbs up or thumbs down.') def check(reaction, user): e = str(reaction.emoji) return e.startswith(('👍', '👎')) res = await client.wait_for_reaction(message=msg, check=check) await client.send_message(message.channel, '{0.user} reacted with {0.reaction.emoji}!'.format(res))
Parameters: - timeout (float) – The number of seconds to wait before returning
None
. - user (
Member
orUser
) – The user the reaction must be from. - emoji (str or
Emoji
or sequence) – The emoji that we are waiting to react with. - message (
Message
) – The message that we want the reaction to be from. - check (function) – A predicate for other complicated checks. The predicate must take
(reaction, user)
as its two parameters, whichreaction
being a
Reaction
anduser
being either aUser
or a
Member
.
Returns: A namedtuple with attributes
reaction
anduser
similar toon_reaction_add()
.Return type: namedtuple
- timeout (float) – The number of seconds to wait before returning
-
event
(coro)¶ -
A decorator that registers an event to listen to.
You can find more info about the events on the documentation below.
The events must be a coroutine, if not,
ClientException
is raised.Examples
Using the basic
event()
decorator:@client.event @asyncio.coroutine def on_ready(): print('Ready!')
Saving characters by using the
async_event()
decorator:@client.async_event def on_ready(): print('Ready!')
-
async_event
(coro)¶ -
A shorthand decorator for
asyncio.coroutine
+event()
.
-
start_private_message
(user)¶ -
This function is a coroutine.
Starts a private message with the user. This allows you to
send_message()
to the user.Note
This method should rarely be called as
send_message()
does it automatically for you.Parameters: user (
User
) – The user to start the private message with.Raises: HTTPException
– The request failed.InvalidArgument
– The user argument was not ofUser
.
-
add_reaction
(message, emoji)¶ -
This function is a coroutine.
Add a reaction to the given message.
The message must be a
Message
that exists. emoji may be a unicode emoji,
or a custom serverEmoji
.Parameters: - message (
Message
) – The message to react to. - emoji (
Emoji
or str) – The emoji to react with.
Raises: HTTPException
– Adding the reaction failed.Forbidden
– You do not have the proper permissions to react to the message.NotFound
– The message or emoji you specified was not found.InvalidArgument
– The message or emoji parameter is invalid.
- message (
-
remove_reaction
(message, emoji, member)¶ -
This function is a coroutine.
Remove a reaction by the member from the given message.
If member != server.me, you need Manage Messages to remove the reaction.
The message must be a
Message
that exists. emoji may be a unicode emoji,
or a custom serverEmoji
.Parameters: - message (
Message
) – The message. - emoji (
Emoji
or str) – The emoji to remove. - member (
Member
) – The member for which to delete the reaction.
Raises: HTTPException
– Removing the reaction failed.Forbidden
– You do not have the proper permissions to remove the reaction.NotFound
– The message or emoji you specified was not found.InvalidArgument
– The message or emoji parameter is invalid.
- message (
-
get_reaction_users
(reaction, limit=100, after=None)¶ -
This function is a coroutine.
Get the users that added a reaction to a message.
Parameters: - reaction (
Reaction
) – The reaction to retrieve users for. - limit (int) – The maximum number of results to return.
- after (
Member
orObject
) – For pagination, reactions are sorted by member.
Raises: HTTPException
– Getting the users for the reaction failed.NotFound
– The message or emoji you specified was not found.InvalidArgument
– The reaction parameter is invalid.
- reaction (
-
clear_reactions
(message)¶ -
This function is a coroutine.
Removes all the reactions from a given message.
You need Manage Messages permission to use this.
Parameters: message (
Message
) – The message to remove all reactions from.Raises: HTTPException
– Removing the reactions failed.Forbidden
– You do not have the proper permissions to remove all the reactions.
-
send_message
(destination, content=None, *, tts=False, embed=None)¶ -
This function is a coroutine.
Sends a message to the destination given with the content given.
The destination could be a
Channel
,PrivateChannel
orServer
.
For convenience it could also be aUser
. If it’s aUser
orPrivateChannel
then it sends the message via private message, otherwise it sends the message to the channel.
If the destination is aServer
then it’s equivalent to calling
Server.default_channel
and sending it there.If it is a
Object
instance then it is assumed to be the
destination ID. The destination ID is a channel so passing in a user
ID will not be a valid destination.Changed in version 0.9.0:
str
being allowed was removed and replaced withObject
.The content must be a type that can convert to a string through
str(content)
.
If the content is set toNone
(the default), then theembed
parameter must
be provided.If the
embed
parameter is provided, it must be of typeEmbed
and
it must be a rich embed type.Parameters: - destination – The location to send the message.
- content – The content of the message to send. If this is missing,
then theembed
parameter must be present. - tts (bool) – Indicates if the message should be sent using text-to-speech.
- embed (
Embed
) – The rich embed for the content.
Raises: HTTPException
– Sending the message failed.Forbidden
– You do not have the proper permissions to send the message.NotFound
– The destination was not found and hence is invalid.InvalidArgument
– The destination parameter is invalid.
Examples
Sending a regular message:
await client.send_message(message.channel, 'Hello')
Sending a TTS message:
await client.send_message(message.channel, 'Goodbye.', tts=True)
Sending an embed message:
em = discord.Embed(title='My Embed Title', description='My Embed Content.', colour=0xDEADBF) em.set_author(name='Someone', icon_url=client.user.default_avatar_url) await client.send_message(message.channel, embed=em)
Returns: The message that was sent. Return type: Message
-
send_typing
(destination)¶ -
This function is a coroutine.
Send a typing status to the destination.
Typing status will go away after 10 seconds, or after a message is sent.
The destination parameter follows the same rules as
send_message()
.Parameters: destination – The location to send the typing update.
-
send_file
(destination, fp, *, filename=None, content=None, tts=False)¶ -
This function is a coroutine.
Sends a message to the destination given with the file given.
The destination parameter follows the same rules as
send_message()
.The
fp
parameter should be either a string denoting the location for a
file or a file-like object. The file-like object passed is not closed
at the end of execution. You are responsible for closing it yourself.Note
If the file-like object passed is opened via
open
then the modes
‘rb’ should be used.The
filename
parameter is the filename of the file.
If this is not given then it defaults tofp.name
or iffp
is a string
then thefilename
will default to the string given. You can overwrite
this value by passing this in.Parameters: - destination – The location to send the message.
- fp – The file-like object or file path to send.
- filename (str) – The filename of the file. Defaults to
fp.name
if it’s available. - content – The content of the message to send along with the file. This is
forced into a string by astr(content)
call. - tts (bool) – If the content of the message should be sent with TTS enabled.
Raises: HTTPException
– Sending the file failed.Returns: The message sent.
Return type: Message
-
delete_message
(message)¶ -
This function is a coroutine.
Deletes a
Message
.Your own messages could be deleted without any proper permissions. However to
delete other people’s messages, you need the proper permissions to do so.Parameters: message (
Message
) – The message to delete.Raises: Forbidden
– You do not have proper permissions to delete the message.HTTPException
– Deleting the message failed.
-
delete_messages
(messages)¶ -
This function is a coroutine.
Deletes a list of messages. This is similar to
delete_message()
except it bulk deletes multiple messages.The channel to check where the message is deleted from is handled via
the first element of the iterable’s.channel.id
attributes. If the
channel is not consistent throughout the entire sequence, then an
HTTPException
will be raised.Usable only by bot accounts.
Parameters: messages (iterable of
Message
) – An iterable of messages denoting which ones to bulk delete.Raises: ClientException
– The number of messages to delete is less than 2 or more than 100.Forbidden
– You do not have proper permissions to delete the messages or
you’re not using a bot account.HTTPException
– Deleting the messages failed.
-
purge_from
(channel, *, limit=100, check=None, before=None, after=None, around=None)¶ -
This function is a coroutine.
Purges a list of messages that meet the criteria given by the predicate
check
. If acheck
is not provided then all messages are deleted
without discrimination.You must have Manage Messages permission to delete messages even if they
are your own. The Read Message History permission is also needed to
retrieve message history.Usable only by bot accounts.
Parameters: - channel (
Channel
) – The channel to purge from. - limit (int) – The number of messages to search through. This is not the number
of messages that will be deleted, though it can be. - check (predicate) – The function used to check if a message should be deleted.
It must take aMessage
as its sole parameter. - before (
Message
or datetime) – The message or date before which all deleted messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time. - after (
Message
or datetime) – The message or date after which all deleted messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time. - around (
Message
or datetime) – The message or date around which all deleted messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time.
Raises: Forbidden
– You do not have proper permissions to do the actions required or
you’re not using a bot account.HTTPException
– Purging the messages failed.
Examples
Deleting bot’s messages
def is_me(m): return m.author == client.user deleted = await client.purge_from(channel, limit=100, check=is_me) await client.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))
Returns: The list of messages that were deleted. Return type: list - channel (
-
edit_message
(message, new_content=None, *, embed=None)¶ -
This function is a coroutine.
Edits a
Message
with the new message content.The new_content must be able to be transformed into a string via
str(new_content)
.If the
new_content
is not provided, thenembed
must be provided, which must
be of typeEmbed
.The
Message
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - message (
Message
) – The message to edit. - new_content – The new content to replace the message with.
- embed (
Embed
) – The new embed to replace the original embed with.
Raises: HTTPException
– Editing the message failed.Returns: The new edited message.
Return type: Message
- message (
-
get_message
(channel, id)¶ -
This function is a coroutine.
Retrieves a single
Message
from aChannel
.This can only be used by bot accounts.
Parameters: - channel (
Channel
orPrivateChannel
) – The text channel to retrieve the message from. - id (str) – The message ID to look for.
Returns: The message asked for.
Return type: Message
Raises: NotFound
– The specified channel or message was not found.Forbidden
– You do not have the permissions required to get a message.HTTPException
– Retrieving the message failed.
- channel (
-
pin_message
(message)¶ -
This function is a coroutine.
Pins a message. You must have Manage Messages permissions
to do this in a non-private channel context.Parameters: message (
Message
) – The message to pin.Raises: Forbidden
– You do not have permissions to pin the message.NotFound
– The message or channel was not found.HTTPException
– Pinning the message failed, probably due to the channel
having more than 50 pinned messages.
-
unpin_message
(message)¶ -
This function is a coroutine.
Unpins a message. You must have Manage Messages permissions
to do this in a non-private channel context.Parameters: message (
Message
) – The message to unpin.Raises: Forbidden
– You do not have permissions to unpin the message.NotFound
– The message or channel was not found.HTTPException
– Unpinning the message failed.
-
pins_from
(channel)¶ -
This function is a coroutine.
Returns a list of
Message
that are currently pinned for
the specifiedChannel
orPrivateChannel
.Parameters: channel (
Channel
orPrivateChannel
) – The channel to look through pins for.Raises: NotFound
– The channel was not found.HTTPException
– Retrieving the pinned messages failed.
-
logs_from
(channel, limit=100, *, before=None, after=None, around=None, reverse=False)¶ -
This function is a coroutine.
This coroutine returns a generator that obtains logs from a specified channel.
Parameters: - channel (
Channel
orPrivateChannel
) – The channel to obtain the logs from. - limit (int) – The number of messages to retrieve.
- before (
Message
or datetime) – The message or date before which all returned messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time. - after (
Message
or datetime) – The message or date after which all returned messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time. - around (
Message
or datetime) – The message or date around which all returned messages must be.
If a date is provided it must be a timezone-naive datetime representing UTC time.
Raises: Forbidden
– You do not have permissions to get channel logs.NotFound
– The channel you are requesting for doesn’t exist.HTTPException
– The request to get logs failed.
Yields: Message
– The message with the message data parsed.Examples
Basic logging:
logs = yield from client.logs_from(channel) for message in logs: if message.content.startswith('!hello'): if message.author == client.user: yield from client.edit_message(message, 'goodbye')
Python 3.5 Usage
counter = 0 async for message in client.logs_from(channel, limit=500): if message.author == client.user: counter += 1
- channel (
-
request_offline_members
(server)¶ -
This function is a coroutine.
Requests previously offline members from the server to be filled up
into theServer.members
cache. This function is usually not
called.When the client logs on and connects to the websocket, Discord does
not provide the library with offline members if the number of members
in the server is larger than 250. You can check if a server is large
ifServer.large
isTrue
.Parameters: server ( Server
or iterable) – The server to request offline members for. If this parameter is a
iterable then it is interpreted as an iterator of servers to
request offline members for.
-
kick
(member)¶ -
This function is a coroutine.
Kicks a
Member
from the server they belong to.Warning
This function kicks the
Member
based on the server it
belongs to, which is accessed viaMember.server
. So you
must have the proper permissions in that server.Parameters: member (
Member
) – The member to kick from their server.Raises: Forbidden
– You do not have the proper permissions to kick.HTTPException
– Kicking failed.
-
ban
(member, delete_message_days=1)¶ -
This function is a coroutine.
Bans a
Member
from the server they belong to.Warning
This function bans the
Member
based on the server it
belongs to, which is accessed viaMember.server
. So you
must have the proper permissions in that server.Parameters: - member (
Member
) – The member to ban from their server. - delete_message_days (int) – The number of days worth of messages to delete from the user
in the server. The minimum is 0 and the maximum is 7.
Raises: Forbidden
– You do not have the proper permissions to ban.HTTPException
– Banning failed.
- member (
-
unban
(server, user)¶ -
This function is a coroutine.
Unbans a
User
from the server they are banned from.Parameters: - server (
Server
) – The server to unban the user from. - user (
User
) – The user to unban.
Raises: Forbidden
– You do not have the proper permissions to unban.HTTPException
– Unbanning failed.
- server (
-
server_voice_state
(member, *, mute=None, deafen=None)¶ -
This function is a coroutine.
Server mutes or deafens a specific
Member
.Warning
This function mutes or un-deafens the
Member
based on the
server it belongs to, which is accessed viaMember.server
.
So you must have the proper permissions in that server.Parameters: - member (
Member
) – The member to unban from their server. - mute (Optional[bool]) – Indicates if the member should be server muted or un-muted.
- deafen (Optional[bool]) – Indicates if the member should be server deafened or un-deafened.
Raises: Forbidden
– You do not have the proper permissions to deafen or mute.HTTPException
– The operation failed.
- member (
-
edit_profile
(password=None, **fields)¶ -
This function is a coroutine.
Edits the current profile of the client.
If a bot account is used then the password field is optional,
otherwise it is required.The
Client.user
object is not modified directly afterwards until the
corresponding WebSocket event is received.Note
To upload an avatar, a bytes-like object must be passed in that
represents the image being uploaded. If this is done through a file
then the file must be opened viaopen('some_filename', 'rb')
and
the bytes-like object is given through the use offp.read()
.The only image formats supported for uploading is JPEG and PNG.
Parameters: - password (str) – The current password for the client’s account. Not used
for bot accounts. - new_password (str) – The new password you wish to change to.
- email (str) – The new email you wish to change to.
- username (str) – The new username you wish to change to.
- avatar (bytes) – A bytes-like object representing the image to upload.
Could beNone
to denote no avatar.
Raises: HTTPException
– Editing your profile failed.InvalidArgument
– Wrong image format passed foravatar
.ClientException
– Password is required for non-bot accounts.
- password (str) – The current password for the client’s account. Not used
-
change_status
(game=None, idle=False)¶ -
This function is a coroutine.
Changes the client’s status.
The game parameter is a Game object (not a string) that represents
a game being played currently.The idle parameter is a boolean parameter that indicates whether the
client should go idle or not.Deprecated since version v0.13.0: Use
change_presence()
instead.Parameters: - game (Optional[
Game
]) – The game being played. None if no game is being played. - idle (bool) – Indicates if the client should go idle.
Raises: InvalidArgument
– If thegame
parameter is notGame
or None. - game (Optional[
-
change_presence
(*, game=None, status=None, afk=False)¶ -
This function is a coroutine.
Changes the client’s presence.
The game parameter is a Game object (not a string) that represents
a game being played currently.Parameters: - game (Optional[
Game
]) – The game being played. None if no game is being played. - status (Optional[
Status
]) – Indicates what status to change to. If None, then
Status.online
is used. - afk (bool) – Indicates if you are going AFK. This allows the discord
client to know how to handle push notifications better
for you in case you are actually idle and not lying.
Raises: InvalidArgument
– If thegame
parameter is notGame
or None. - game (Optional[
-
change_nickname
(member, nickname)¶ -
This function is a coroutine.
Changes a member’s nickname.
You must have the proper permissions to change someone’s
(or your own) nickname.Parameters: - member (
Member
) – The member to change the nickname for. - nickname (Optional[str]) – The nickname to change it to.
None
to remove
the nickname.
Raises: Forbidden
– You do not have permissions to change the nickname.HTTPException
– Changing the nickname failed.
- member (
-
edit_channel
(channel, **options)¶ -
This function is a coroutine.
Edits a
Channel
.You must have the proper permissions to edit the channel.
To move the channel’s position use
move_channel()
instead.The
Channel
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - channel (
Channel
) – The channel to update. - name (str) – The new channel name.
- topic (str) – The new channel’s topic.
- bitrate (int) – The new channel’s bitrate. Voice only.
- user_limit (int) – The new channel’s user limit. Voice only.
Raises: Forbidden
– You do not have permissions to edit the channel.HTTPException
– Editing the channel failed.
- channel (
-
move_channel
(channel, position)¶ -
This function is a coroutine.
Moves the specified
Channel
to the given position in the GUI.
Note that voice channels and text channels have different position values.The
Channel
object is not directly modified afterwards until the
corresponding WebSocket event is received.Warning
Object
instances do not work with this function.Parameters: - channel (
Channel
) – The channel to change positions of. - position (int) – The position to insert the channel to.
Raises: InvalidArgument
– If position is less than 0 or greater than the number of channels.Forbidden
– You do not have permissions to change channel order.HTTPException
– If moving the channel failed, or you are of too low rank to move the channel.
- channel (
-
create_channel
(server, name, *overwrites, type=None)¶ -
This function is a coroutine.
Creates a
Channel
in the specifiedServer
.Note that you need the proper permissions to create the channel.
The
overwrites
argument list can be used to create a ‘secret’
channel upon creation. A namedtuple ofChannelPermissions
is exposed to create a channel-specific permission overwrite in a more
self-documenting matter. You can also use a regular tuple of(target, overwrite)
where theoverwrite
expected has to be of typePermissionOverwrite
.Examples
Creating a voice channel:
await client.create_channel(server, 'Voice', type=discord.ChannelType.voice)
Creating a ‘secret’ text channel:
everyone_perms = discord.PermissionOverwrite(read_messages=False) my_perms = discord.PermissionOverwrite(read_messages=True) everyone = discord.ChannelPermissions(target=server.default_role, overwrite=everyone_perms) mine = discord.ChannelPermissions(target=server.me, overwrite=my_perms) await client.create_channel(server, 'secret', everyone, mine)
Or in a more ‘compact’ way:
everyone = discord.PermissionOverwrite(read_messages=False) mine = discord.PermissionOverwrite(read_messages=True) await client.create_channel(server, 'secret', (server.default_role, everyone), (server.me, mine))
Parameters: - server (
Server
) – The server to create the channel in. - name (str) – The channel’s name.
- type (
ChannelType
) – The type of channel to create. Defaults toChannelType.text
. - overwrites – An argument list of channel specific overwrites to apply on the channel on
creation. Useful for creating ‘secret’ channels.
Raises: Forbidden
– You do not have the proper permissions to create the channel.NotFound
– The server specified was not found.HTTPException
– Creating the channel failed.InvalidArgument
– The permission overwrite array is not in proper form.
Returns: The channel that was just created. This channel is
different than the one that will be added in cache.Return type: Channel
- server (
-
delete_channel
(channel)¶ -
This function is a coroutine.
Deletes a
Channel
.In order to delete the channel, the client must have the proper permissions
in the server the channel belongs to.Parameters: channel (
Channel
) – The channel to delete.Raises: Forbidden
– You do not have proper permissions to delete the channel.NotFound
– The specified channel was not found.HTTPException
– Deleting the channel failed.
-
leave_server
(server)¶ -
This function is a coroutine.
Leaves a
Server
.Note
You cannot leave the server that you own, you must delete it instead
viadelete_server()
.Parameters: server ( Server
) – The server to leave.Raises: HTTPException
– If leaving the server failed.
-
delete_server
(server)¶ -
This function is a coroutine.
Deletes a
Server
. You must be the server owner to delete the
server.Parameters: server (
Server
) – The server to delete.Raises: HTTPException
– If deleting the server failed.Forbidden
– You do not have permissions to delete the server.
-
create_server
(name, region=None, icon=None)¶ -
This function is a coroutine.
Creates a
Server
.Bot accounts generally are not allowed to create servers.
See Discord’s official documentation for more info.Parameters: - name (str) – The name of the server.
- region (
ServerRegion
) – The region for the voice communication server.
Defaults toServerRegion.us_west
. - icon (bytes) – The bytes-like object representing the icon. See
edit_profile()
for more details on what is expected.
Raises: HTTPException
– Server creation failed.InvalidArgument
– Invalid icon image format given. Must be PNG or JPG.
Returns: The server created. This is not the same server that is
added to cache.Return type: Server
-
edit_server
(server, **fields)¶ -
This function is a coroutine.
Edits a
Server
.You must have the proper permissions to edit the server.
The
Server
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - server (
Server
) – The server to edit. - name (str) – The new name of the server.
- icon (bytes) – A bytes-like object representing the icon. See
edit_profile()
for more details. Could beNone
to denote no icon. - splash (bytes) – A bytes-like object representing the invite splash. See
edit_profile()
for more details. Could beNone
to denote
no invite splash. Only available for partnered servers with
INVITE_SPLASH
feature. - region (
ServerRegion
) – The new region for the server’s voice communication. - afk_channel (Optional[
Channel
]) – The new channel that is the AFK channel. Could beNone
for no AFK channel. - afk_timeout (int) – The number of seconds until someone is moved to the AFK channel.
- owner (
Member
) – The new owner of the server to transfer ownership to. Note that you must
be owner of the server to do this. - verification_level (
VerificationLevel
) – The new verification level for the server.
Raises: Forbidden
– You do not have permissions to edit the server.NotFound
– The server you are trying to edit does not exist.HTTPException
– Editing the server failed.InvalidArgument
– The image format passed in toicon
is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
server and request an ownership transfer.
- server (
-
get_bans
(server)¶ -
This function is a coroutine.
Retrieves all the
User
s that are banned from the specified
server.You must have proper permissions to get this information.
Parameters: server (
Server
) – The server to get ban information from.Raises: Forbidden
– You do not have proper permissions to get the information.HTTPException
– An error occurred while fetching the information.
Returns: A list of
User
that have been banned.Return type: list
-
prune_members
(server, *, days)¶ -
This function is a coroutine.
Prunes a
Server
from its inactive members.The inactive members are denoted if they have not logged on in
days
number of days and they have no roles.You must have the “Kick Members” permission to use this.
To check how many members you would prune without actually pruning,
see theestimate_pruned_members()
function.Parameters: - server (
Server
) – The server to prune from. - days (int) – The number of days before counting as inactive.
Raises: Forbidden
– You do not have permissions to prune members.HTTPException
– An error occurred while pruning members.InvalidArgument
– An integer was not passed fordays
.
Returns: The number of members pruned.
Return type: int
- server (
-
estimate_pruned_members
(server, *, days)¶ -
This function is a coroutine.
Similar to
prune_members()
except instead of actually
pruning members, it returns how many members it would prune
from the server had it been called.Parameters: - server (
Server
) – The server to estimate a prune from. - days (int) – The number of days before counting as inactive.
Raises: Forbidden
– You do not have permissions to prune members.HTTPException
– An error occurred while fetching the prune members estimate.InvalidArgument
– An integer was not passed fordays
.
Returns: The number of members estimated to be pruned.
Return type: int
- server (
-
create_custom_emoji
(server, *, name, image)¶ -
This function is a coroutine.
Creates a custom
Emoji
for aServer
.This endpoint is only allowed for user bots or white listed
bots. If this is done by a user bot then this is a local
emoji that can only be used inside that server.There is currently a limit of 50 local emotes per server.
Parameters: - server (
Server
) – The server to add the emoji to. - name (str) – The emoji name. Must be at least 2 characters.
- image (bytes) – The bytes-like object representing the image data to use.
Only JPG and PNG images are supported.
Returns: The created emoji.
Return type: Emoji
Raises: Forbidden
– You are not allowed to create emojis.HTTPException
– An error occurred creating an emoji.
- server (
-
delete_custom_emoji
(emoji)¶ -
This function is a coroutine.
Deletes a custom
Emoji
from aServer
.This follows the same rules as
create_custom_emoji()
.Parameters: emoji (
Emoji
) – The emoji to delete.Raises: Forbidden
– You are not allowed to delete emojis.HTTPException
– An error occurred deleting the emoji.
-
edit_custom_emoji
(emoji, *, name)¶ -
This function is a coroutine.
Edits a
Emoji
.Parameters: - emoji (
Emoji
) – The emoji to edit. - name (str) – The new emoji name.
Raises: Forbidden
– You are not allowed to edit emojis.HTTPException
– An error occurred editing the emoji.
- emoji (
-
create_invite
(destination, **options)¶ -
This function is a coroutine.
Creates an invite for the destination which could be either a
Server
orChannel
.Parameters: - destination – The
Server
orChannel
to create the invite to. - max_age (int) – How long the invite should last. If it’s 0 then the invite
doesn’t expire. Defaults to 0. - max_uses (int) – How many uses the invite could be used for. If it’s 0 then there
are unlimited uses. Defaults to 0. - temporary (bool) – Denotes that the invite grants temporary membership
(i.e. they get kicked after they disconnect). Defaults to False. - unique (bool) – Indicates if a unique invite URL should be created. Defaults to True.
If this is set to False then it will return a previously created
invite.
Raises: HTTPException
– Invite creation failed.Returns: The invite that was created.
Return type: Invite
- destination – The
-
get_invite
(url)¶ -
This function is a coroutine.
Gets a
Invite
from a discord.gg URL or ID.Note
If the invite is for a server you have not joined, the server and channel
attributes of the returned invite will beObject
with the names
patched in.Parameters: url (str) – The discord invite ID or URL (must be a discord.gg URL).
Raises: NotFound
– The invite has expired or is invalid.HTTPException
– Getting the invite failed.
Returns: The invite from the URL/ID.
Return type: Invite
-
invites_from
(server)¶ -
This function is a coroutine.
Returns a list of all active instant invites from a
Server
.You must have proper permissions to get this information.
Parameters: server (
Server
) – The server to get invites from.Raises: Forbidden
– You do not have proper permissions to get the information.HTTPException
– An error occurred while fetching the information.
Returns: The list of invites that are currently active.
Return type: list of
Invite
-
accept_invite
(invite)¶ -
This function is a coroutine.
Accepts an
Invite
, URL or ID to an invite.The URL must be a discord.gg URL. e.g. “http://discord.gg/codehere”.
An ID for the invite is just the “codehere” portion of the invite URL.Parameters: invite – The
Invite
or URL to an invite to accept.Raises: HTTPException
– Accepting the invite failed.NotFound
– The invite is invalid or expired.Forbidden
– You are a bot user and cannot use this endpoint.
-
delete_invite
(invite)¶ -
This function is a coroutine.
Revokes an
Invite
, URL, or ID to an invite.The
invite
parameter follows the same rules as
accept_invite()
.Parameters: invite – The invite to revoke.
Raises: Forbidden
– You do not have permissions to revoke invites.NotFound
– The invite is invalid or expired.HTTPException
– Revoking the invite failed.
-
move_role
(server, role, position)¶ -
This function is a coroutine.
Moves the specified
Role
to the given position in theServer
.The
Role
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - server (
Server
) – The server the role belongs to. - role (
Role
) – The role to edit. - position (int) – The position to insert the role to.
Raises: InvalidArgument
– If position is 0, or role is server.default_roleForbidden
– You do not have permissions to change role order.HTTPException
– If moving the role failed, or you are of too low rank to move the role.
- server (
-
edit_role
(server, role, **fields)¶ -
This function is a coroutine.
Edits the specified
Role
for the entireServer
.The
Role
object is not directly modified afterwards until the
corresponding WebSocket event is received.All fields except
server
androle
are optional. To change
the position of a role, usemove_role()
instead.Changed in version 0.8.0: Editing now uses keyword arguments instead of editing the
Role
object directly.Parameters: - server (
Server
) – The server the role belongs to. - role (
Role
) – The role to edit. - name (str) – The new role name to change to.
- permissions (
Permissions
) – The new permissions to change to. - colour (
Colour
) – The new colour to change to. (aliased to color as well) - hoist (bool) – Indicates if the role should be shown separately in the online list.
- mentionable (bool) – Indicates if the role should be mentionable by others.
Raises: Forbidden
– You do not have permissions to change the role.HTTPException
– Editing the role failed.
- server (
-
delete_role
(server, role)¶ -
This function is a coroutine.
Deletes the specified
Role
for the entireServer
.Parameters: - server (
Server
) – The server the role belongs to. - role (
Role
) – The role to delete.
Raises: Forbidden
– You do not have permissions to delete the role.HTTPException
– Deleting the role failed.
- server (
-
add_roles
(member, *roles)¶ -
This function is a coroutine.
Gives the specified
Member
a number ofRole
s.You must have the proper permissions to use this function.
The
Member
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - member (
Member
) – The member to give roles to. - *roles – An argument list of
Role
s to give the member.
Raises: Forbidden
– You do not have permissions to add roles.HTTPException
– Adding roles failed.
- member (
-
remove_roles
(member, *roles)¶ -
This function is a coroutine.
Removes the
Role
s from theMember
.You must have the proper permissions to use this function.
The
Member
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - member (
Member
) – The member to revoke roles from. - *roles – An argument list of
Role
s to revoke the member.
Raises: Forbidden
– You do not have permissions to revoke roles.HTTPException
– Removing roles failed.
- member (
-
replace_roles
(member, *roles)¶ -
This function is a coroutine.
Replaces the
Member
’s roles.You must have the proper permissions to use this function.
This function replaces all roles that the member has.
For example if the member has roles[a, b, c]
and the
call isclient.replace_roles(member, d, e, c)
then
the member has the roles[d, e, c]
.The
Member
object is not directly modified afterwards until the
corresponding WebSocket event is received.Parameters: - member (
Member
) – The member to replace roles from. - *roles – An argument list of
Role
s to replace the roles with.
Raises: Forbidden
– You do not have permissions to revoke roles.HTTPException
– Removing roles failed.
- member (
-
create_role
(server, **fields)¶ -
This function is a coroutine.
Creates a
Role
.This function is similar to
edit_role
in both
the fields taken and exceptions thrown.Returns: The newly created role. This not the same role that
is stored in cache.Return type: Role
-
edit_channel_permissions
(channel, target, overwrite=None)¶ -
This function is a coroutine.
Sets the channel specific permission overwrites for a target in the
specifiedChannel
.The
target
parameter should either be aMember
or a
Role
that belongs to the channel’s server.You must have the proper permissions to do this.
Examples
Setting allow and deny:
overwrite = discord.PermissionOverwrite() overwrite.read_messages = True overwrite.ban_members = False await client.edit_channel_permissions(message.channel, message.author, overwrite)
Parameters: - channel (
Channel
) – The channel to give the specific permissions for. - target – The
Member
orRole
to overwrite permissions for. - overwrite (
PermissionOverwrite
) – The permissions to allow and deny to the target.
Raises: Forbidden
– You do not have permissions to edit channel specific permissions.NotFound
– The channel specified was not found.HTTPException
– Editing channel specific permissions failed.InvalidArgument
– The overwrite parameter was not of typePermissionOverwrite
or the target type was notRole
orMember
.
- channel (
-
delete_channel_permissions
(channel, target)¶ -
This function is a coroutine.
Removes a channel specific permission overwrites for a target
in the specifiedChannel
.The target parameter follows the same rules as
edit_channel_permissions()
.You must have the proper permissions to do this.
Parameters: - channel (
Channel
) – The channel to give the specific permissions for. - target – The
Member
orRole
to overwrite permissions for.
Raises: Forbidden
– You do not have permissions to delete channel specific permissions.NotFound
– The channel specified was not found.HTTPException
– Deleting channel specific permissions failed.
- channel (
-
move_member
(member, channel)¶ -
This function is a coroutine.
Moves a
Member
to a different voice channel.You must have proper permissions to do this.
Note
You cannot pass in a
Object
instead of aChannel
object in this function.Parameters: - member (
Member
) – The member to move to another voice channel. - channel (
Channel
) – The voice channel to move the member to.
Raises: InvalidArgument
– The channel provided is not a voice channel.HTTPException
– Moving the member failed.Forbidden
– You do not have permissions to move the member.
- member (
-
join_voice_channel
(channel)¶ -
This function is a coroutine.
Joins a voice channel and creates a
VoiceClient
to
establish your connection to the voice server.After this function is successfully called,
voice
is
set to the returnedVoiceClient
.Parameters: channel (
Channel
) – The voice channel to join to.Raises: InvalidArgument
– The channel was not a voice channel.asyncio.TimeoutError
– Could not connect to the voice channel in time.ClientException
– You are already connected to a voice channel.OpusNotLoaded
– The opus library has not been loaded.
Returns: A voice client that is fully connected to the voice server.
Return type: VoiceClient
-
is_voice_connected
(server)¶ -
Indicates if we are currently connected to a voice channel in the
specified server.Parameters: server ( Server
) – The server to query if we’re connected to it.
-
voice_client_in
(server)¶ -
Returns the voice client associated with a server.
If no voice client is found then
None
is returned.Parameters: server ( Server
) – The server to query if we have a voice client for.Returns: The voice client associated with the server. Return type: VoiceClient
-
group_call_in
(channel)¶ -
Returns the
GroupCall
associated with a private channel.If no group call is found then
None
is returned.Parameters: channel ( PrivateChannel
) – The group private channel to query the group call for.Returns: The group call. Return type: Optional[ GroupCall
]
-
application_info
()¶ -
This function is a coroutine.
Retrieve’s the bot’s application information.
Returns: A namedtuple representing the application info. Return type: AppInfo
Raises: HTTPException
– Retrieving the information failed somehow.
-
get_user_info
(user_id)¶ -
This function is a coroutine.
Retrieves a
User
based on their ID. This can only
be used by bot accounts. You do not have to share any servers
with the user to get this information, however many operations
do require that you do.Parameters: user_id (str) – The user’s ID to fetch from.
Returns: The user you requested.
Return type: User
Raises: NotFound
– A user with this ID does not exist.HTTPException
– Fetching the user failed.
- max_messages (Optional[int]) – The maximum number of messages to store in
Voice¶
-
class
discord.
VoiceClient
(user, main_ws, session_id, channel, data, loop)¶ -
Represents a Discord voice connection.
This client is created solely through
Client.join_voice_channel()
and its only purpose is to transmit voice.Warning
In order to play audio, you must have loaded the opus library
throughopus.load_opus()
.If you don’t do this then the library will not be able to
transmit audio.-
session_id
¶ -
str – The voice connection session ID.
-
token
¶ -
str – The voice connection token.
-
user
¶ -
User
– The user connected to voice.
-
endpoint
¶ -
str – The endpoint we are connecting to.
-
channel
¶ -
Channel
– The voice channel connected to.
-
server
¶ -
Server
– The server the voice channel is connected to.
Shorthand forchannel.server
.
-
loop
¶ -
The event loop that the voice client is running on.
-
poll_voice_ws
()¶ -
This function is a coroutine.
Reads from the voice websocket while connected.
-
disconnect
()¶ -
This function is a coroutine.
Disconnects all connections to the voice client.
In order to reconnect, you must create another voice client
usingClient.join_voice_channel()
.
-
move_to
(channel)¶ -
This function is a coroutine.
Moves you to a different voice channel.
Warning
Object
instances do not work with this function.Parameters: channel ( Channel
) – The channel to move to. Must be a voice channel.Raises: InvalidArgument
– Not a voice channel.
-
is_connected
()¶ -
bool : Indicates if the voice client is connected to voice.
-
create_ffmpeg_player
(filename, *, use_avconv=False, pipe=False, stderr=None, options=None, before_options=None, headers=None, after=None)¶ -
Creates a stream player for ffmpeg that launches in a separate thread to play
audio.The ffmpeg player launches a subprocess of
ffmpeg
to a specific
filename and then plays that file.You must have the ffmpeg or avconv executable in your path environment variable
in order for this to work.The operations that can be done on the player are the same as those in
create_stream_player()
.Examples
Basic usage:
voice = await client.join_voice_channel(channel) player = voice.create_ffmpeg_player('cool.mp3') player.start()
Parameters: - filename – The filename that ffmpeg will take and convert to PCM bytes.
Ifpipe
is True then this is a file-like object that is
passed to the stdin offfmpeg
. - use_avconv (bool) – Use
avconv
instead offfmpeg
. - pipe (bool) – If true, denotes that
filename
parameter will be passed
to the stdin of ffmpeg. - stderr – A file-like object or
subprocess.PIPE
to pass to the Popen
constructor. - options (str) – Extra command line flags to pass to
ffmpeg
after the-i
flag. - before_options (str) – Command line flags to pass to
ffmpeg
before the-i
flag. - headers (dict) – HTTP headers dictionary to pass to
-headers
command line option - after (callable) – The finalizer that is called after the stream is done being
played. All exceptions the finalizer throws are silently discarded.
Raises: ClientException
– Popen failed to due to an error inffmpeg
oravconv
.Returns: A stream player with specific operations.
Seecreate_stream_player()
.Return type: StreamPlayer
- filename – The filename that ffmpeg will take and convert to PCM bytes.
-
create_ytdl_player
(url, *, ytdl_options=None, **kwargs)¶ -
This function is a coroutine.
Creates a stream player for youtube or other services that launches
in a separate thread to play the audio.The player uses the
youtube_dl
python library to get the information
required to get audio from the URL. Since this uses an external library,
you must install it yourself. You can do so by calling
pip install youtube_dl
.You must have the ffmpeg or avconv executable in your path environment
variable in order for this to work.The operations that can be done on the player are the same as those in
create_stream_player()
. The player has been augmented and enhanced
to have some info extracted from the URL. If youtube-dl fails to extract
the information then the attribute isNone
. Theyt
,url
, and
download_url
attributes are always available.Operation Description player.yt The YoutubeDL <ytdl> instance. player.url The URL that is currently playing. player.download_url The URL that is currently being downloaded to ffmpeg. player.title The title of the audio stream. player.description The description of the audio stream. player.uploader The uploader of the audio stream. player.upload_date A datetime.date object of when the stream was uploaded. player.duration The duration of the audio in seconds. player.likes How many likes the audio stream has. player.dislikes How many dislikes the audio stream has. player.is_live Checks if the audio stream is currently livestreaming. player.views How many views the audio stream has. Examples
Basic usage:
voice = await client.join_voice_channel(channel) player = await voice.create_ytdl_player('https://www.youtube.com/watch?v=d62TYemN6MQ') player.start()
Parameters: - url (str) – The URL that
youtube_dl
will take and download audio to pass
toffmpeg
oravconv
to convert to PCM bytes. - ytdl_options (dict) – A dictionary of options to pass into the
YoutubeDL
instance.
See the documentation for more details. - **kwargs – The rest of the keyword arguments are forwarded to
create_ffmpeg_player()
.
Raises: ClientException
– Popen failure from eitherffmpeg
/avconv
.Returns: An augmented StreamPlayer that uses ffmpeg.
Seecreate_stream_player()
for base operations.Return type: StreamPlayer
- url (str) – The URL that
-
encoder_options
(*, sample_rate, channels=2)¶ -
Sets the encoder options for the OpusEncoder.
Calling this after you create a stream player
viacreate_ffmpeg_player()
orcreate_stream_player()
has no effect.Parameters: - sample_rate (int) – Sets the sample rate of the OpusEncoder. The unit is in Hz.
- channels (int) – Sets the number of channels for the OpusEncoder.
2 for stereo, 1 for mono.
Raises: InvalidArgument
– The values provided are invalid.
-
create_stream_player
(stream, *, after=None)¶ -
Creates a stream player that launches in a separate thread to
play audio.The stream player assumes that
stream.read
is a valid function
that returns a bytes-like object.The finalizer,
after
is called after the stream has been exhausted
or an error occurred (see below).The following operations are valid on the
StreamPlayer
object:Operation Description player.start() Starts the audio stream. player.stop() Stops the audio stream. player.is_done() Returns a bool indicating if the stream is done. player.is_playing() Returns a bool indicating if the stream is playing. player.pause() Pauses the audio stream. player.resume() Resumes the audio stream. player.volume Allows you to set the volume of the stream. 1.0 is
equivalent to 100% and 0.0 is equal to 0%. The
maximum the volume can be set to is 2.0 for 200%.player.error The exception that stopped the player. If no error
happened, then this returns None.The stream must have the same sampling rate as the encoder and the same
number of channels. The defaults are 48000 Hz and 2 channels. You
could change the encoder options by usingencoder_options()
but this must be called before this function.If an error happens while the player is running, the exception is caught and
the player is then stopped. The caught exception could then be retrieved
viaplayer.error
. When the player is stopped in this matter, the
finalizer underafter
is called.Parameters: - stream – The stream object to read from.
- after – The finalizer that is called after the stream is exhausted.
All exceptions it throws are silently discarded. This function
can have either no parameters or a single parameter taking in the
current player.
Returns: A stream player with the operations noted above.
Return type: StreamPlayer
-
play_audio
(data, *, encode=True)¶ -
Sends an audio packet composed of the data.
You must be connected to play audio.
Parameters: - data (bytes) – The bytes-like object denoting PCM or Opus voice data.
- encode (bool) – Indicates if
data
should be encoded into Opus.
Raises: ClientException
– You are not connected.OpusError
– Encoding the data failed.
-
Opus Library¶
-
discord.opus.
load_opus
(name)¶ -
Loads the libopus shared library for use with voice.
If this function is not called then the library uses the function
ctypes.util.find_library and then loads that one
if available.Not loading a library leads to voice not working.
This function propagates the exceptions thrown.
Warning
The bitness of the library must match the bitness of your python
interpreter. If the library is 64-bit then your python interpreter
must be 64-bit as well. Usually if there’s a mismatch in bitness then
the load will throw an exception.Note
On Windows, the .dll extension is not necessary. However, on Linux
the full extension is required to load the library, e.g.libopus.so.1
.
On Linux however, find library will usually find the library automatically
without you having to call this.Parameters: name (str) – The filename of the shared library.
-
discord.opus.
is_loaded
()¶ -
Function to check if opus lib is successfully loaded either
via thectypes.util.find_library
call ofload_opus()
.This must return
True
for voice to work.Returns: Indicates if the opus library has been loaded. Return type: bool
Event Reference¶
This page outlines the different types of events listened by Client
.
There are two ways to register an event, the first way is through the use of
Client.event()
. The second way is through subclassing Client
and
overriding the specific events. For example:
import discord class MyClient(discord.Client): @asyncio.coroutine def on_message(self, message): yield from self.send_message(message.channel, 'Hello World!')
If an event handler raises an exception, on_error()
will be called
to handle it, which defaults to print a traceback and ignore the exception.
Warning
All the events must be a coroutine. If they aren’t, then you might get unexpected
errors. In order to turn a function into a coroutine they must either be decorated
with @asyncio.coroutine
or in Python 3.5+ be defined using the async def
declaration.
The following two functions are examples of coroutine functions:
async def on_ready(): pass @asyncio.coroutine def on_ready(): pass
Since this can be a potentially common mistake, there is a helper
decorator, Client.async_event()
to convert a basic function
into a coroutine and an event at the same time. Note that it is
not necessary if you use async def
.
New in version 0.7.0: Subclassing to listen to events.
-
discord.
on_ready
()¶ -
Called when the client is done preparing the data received from Discord. Usually after login is successful
and theClient.servers
and co. are filled up.Warning
This function is not guaranteed to be the first event called.
Likewise, this function is not guaranteed to only be called
once. This library implements reconnection logic and thus will
end up calling this event whenever a RESUME request fails.
-
discord.
on_resumed
()¶ -
Called when the client has resumed a session.
-
discord.
on_error
(event, *args, **kwargs)¶ -
Usually when an event raises an uncaught exception, a traceback is
printed to stderr and the exception is ignored. If you want to
change this behaviour and handle the exception for whatever reason
yourself, this event can be overridden. Which, when done, will
supress the default action of printing the traceback.The information of the exception rasied and the exception itself can
be retreived with a standard call tosys.exc_info()
.If you want exception to propogate out of the
Client
class
you can define anon_error
handler consisting of a single empty
raise
statement. Exceptions raised byon_error
will not be
handled in any way byClient
.Parameters: - event – The name of the event that raised the exception.
- args – The positional arguments for the event that raised the
exception. - kwargs – The keyword arguments for the event that raised the
execption.
-
discord.
on_message
(message)¶ -
Called when a message is created and sent to a server.
Parameters: message – A Message
of the current message.
-
discord.
on_socket_raw_receive
(msg)¶ -
Called whenever a message is received from the websocket, before
it’s processed.This event is always dispatched when a message is
received and the passed data is not processed in any way.This is only really useful for grabbing the websocket stream and
debugging purposes.Note
This is only for the messages received from the client
websocket. The voice websocket will not trigger this event.Parameters: msg – The message passed in from the websocket library.
Could bebytes
for a binary message orstr
for a regular message.
-
discord.
on_socket_raw_send
(payload)¶ -
Called whenever a send operation is done on the websocket before the
message is sent. The passed parameter is the message that is to
sent to the websocket.This is only really useful for grabbing the websocket stream and
debugging purposes.Note
This is only for the messages received from the client
websocket. The voice websocket will not trigger this event.Parameters: payload – The message that is about to be passed on to the
websocket library. It can bebytes
to denote a binary
message orstr
to denote a regular text message.
-
discord.
on_message_delete
(message)¶ -
Called when a message is deleted. If the message is not found in the
Client.messages
cache, then these events will not be called. This
happens if the message is too old or the client is participating in high
traffic servers. To fix this, increase themax_messages
option of
Client
.Parameters: message – A Message
of the deleted message.
-
discord.
on_message_edit
(before, after)¶ -
Called when a message receives an update event. If the message is not found
in theClient.messages
cache, then these events will not be called.
This happens if the message is too old or the client is participating in high
traffic servers. To fix this, increase themax_messages
option ofClient
.The following non-exhaustive cases trigger this event:
- A message has been pinned or unpinned.
- The message content has been changed.
-
- The message has received an embed.
-
- For performance reasons, the embed server does not do this in a “consistent” manner.
- A call message has received an update to its participants or ending time.
Parameters: - before – A
Message
of the previous version of the message. - after – A
Message
of the current version of the message.
-
discord.
on_reaction_add
(reaction, user)¶ -
Called when a message has a reaction added to it. Similar to on_message_edit,
if the message is not found in theClient.messages
cache, then this
event will not be called.Note
To get the message being reacted, access it via
Reaction.message
.Parameters: - reaction – A
Reaction
showing the current state of the reaction. - user – A
User
orMember
of the user who added the reaction.
- reaction – A
-
discord.
on_reaction_remove
(reaction, user)¶ -
Called when a message has a reaction removed from it. Similar to on_message_edit,
if the message is not found in theClient.messages
cache, then this event
will not be called.Note
To get the message being reacted, access it via
Reaction.message
.Parameters: - reaction – A
Reaction
showing the current state of the reaction. - user – A
User
orMember
of the user who removed the reaction.
- reaction – A
-
discord.
on_reaction_clear
(message, reactions)¶ -
Called when a message has all its reactions removed from it. Similar to on_message_edit,
if the message is not found in theClient.messages
cache, then this event
will not be called.Parameters: - message – The
Message
that had its reactions cleared. - reactions – A list of
Reaction
s that were removed.
- message – The
-
discord.
on_channel_delete
(channel)¶ -
discord.
on_channel_create
(channel)¶ -
Called whenever a channel is removed or added from a server.
Note that you can get the server from
Channel.server
.
on_channel_create()
could also pass in aPrivateChannel
depending
on the value ofChannel.is_private
.Parameters: channel – The Channel
that got added or deleted.
-
discord.
on_channel_update
(before, after)¶ -
Called whenever a channel is updated. e.g. changed name, topic, permissions.
Parameters: - before – The
Channel
that got updated with the old info. - after – The
Channel
that got updated with the updated info.
- before – The
-
discord.
on_member_join
(member)¶ -
discord.
on_member_remove
(member)¶ -
Called when a
Member
leaves or joins aServer
.Parameters: member – The Member
that joined or left.
-
discord.
on_member_update
(before, after)¶ -
Called when a
Member
updates their profile.This is called when one or more of the following things change:
- status
- game playing
- avatar
- nickname
- roles
Parameters: - before – The
Member
that updated their profile with the old info. - after – The
Member
that updated their profile with the updated info.
-
discord.
on_server_join
(server)¶ -
Called when a
Server
is either created by theClient
or when the
Client
joins a server.Parameters: server – The class:Server that was joined.
-
discord.
on_server_remove
(server)¶ -
Called when a
Server
is removed from theClient
.This happens through, but not limited to, these circumstances:
- The client got banned.
- The client got kicked.
- The client left the server.
- The client or the server owner deleted the server.
In order for this event to be invoked then the
Client
must have
been part of the server to begin with. (i.e. it is part ofClient.servers
)Parameters: server – The Server
that got removed.
-
discord.
on_server_update
(before, after)¶ -
Called when a
Server
updates, for example:- Changed name
- Changed AFK channel
- Changed AFK timeout
- etc
Parameters: - before – The
Server
prior to being updated. - after – The
Server
after being updated.
-
discord.
on_server_role_create
(role)¶ -
discord.
on_server_role_delete
(role)¶ -
Called when a
Server
creates or deletes a newRole
.To get the server it belongs to, use
Role.server
.Parameters: role – The Role
that was created or deleted.
-
discord.
on_server_role_update
(before, after)¶ -
Called when a
Role
is changed server-wide.Parameters: - before – The
Role
that updated with the old info. - after – The
Role
that updated with the updated info.
- before – The
-
discord.
on_server_emojis_update
(before, after)¶ -
Called when a
Server
adds or removesEmoji
.Parameters: - before – A list of
Emoji
before the update. - after – A list of
Emoji
after the update.
- before – A list of
-
discord.
on_server_available
(server)¶ -
discord.
on_server_unavailable
(server)¶ -
Called when a server becomes available or unavailable. The server must have
existed in theClient.servers
cache.Parameters: server – The Server
that has changed availability.
-
discord.
on_voice_state_update
(before, after)¶ -
Called when a
Member
changes their voice state.The following, but not limited to, examples illustrate when this event is called:
- A member joins a voice room.
- A member leaves a voice room.
- A member is muted or deafened by their own accord.
- A member is muted or deafened by a server administrator.
Parameters: - before – The
Member
whose voice state changed prior to the changes. - after – The
Member
whose voice state changed after the changes.
-
discord.
on_member_ban
(member)¶ -
Called when a
Member
gets banned from aServer
.You can access the server that the member got banned from via
Member.server
.Parameters: member – The member that got banned.
-
discord.
on_member_unban
(server, user)¶ -
Called when a
User
gets unbanned from aServer
.Parameters: - server – The server the user got unbanned from.
- user – The user that got unbanned.
-
discord.
on_typing
(channel, user, when)¶ -
Called when someone begins typing a message.
The
channel
parameter could either be aPrivateChannel
or a
Channel
. Ifchannel
is aPrivateChannel
then the
user
parameter is aUser
, otherwise it is aMember
.Parameters: - channel – The location where the typing originated from.
- user – The user that started typing.
- when – A
datetime.datetime
object representing when typing started.
-
discord.
on_group_join
(channel, user)¶ -
discord.
on_group_remove
(channel, user)¶ -
Called when someone joins or leaves a group, i.e. a
PrivateChannel
with aPrivateChannel.type
ofChannelType.group
.Parameters: - channel – The group that the user joined or left.
- user – The user that joined or left.
Utility Functions¶
-
discord.utils.
find
(predicate, seq)¶ -
A helper to return the first element found in the sequence
that meets the predicate. For example:member = find(lambda m: m.name == 'Mighty', channel.server.members)
would find the first
Member
whose name is ‘Mighty’ and return it.
If an entry is not found, thenNone
is returned.This is different from filter due to the fact it stops the moment it finds
a valid entry.Parameters: - predicate – A function that returns a boolean-like result.
- seq (iterable) – The iterable to search through.
-
discord.utils.
get
(iterable, **attrs)¶ -
A helper that returns the first element in the iterable that meets
all the traits passed inattrs
. This is an alternative for
discord.utils.find()
.When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them.To have a nested attribute search (i.e. search by
x.y
) then
pass inx__y
as the keyword argument.If nothing is found that matches the attributes passed, then
None
is returned.Examples
Basic usage:
member = discord.utils.get(message.server.members, name='Foo')
Multiple attribute matching:
channel = discord.utils.get(server.channels, name='Foo', type=ChannelType.voice)
Nested attribute matching:
channel = discord.utils.get(client.get_all_channels(), server__name='Cool', name='general')
Parameters: - iterable – An iterable to search through.
- **attrs – Keyword arguments that denote attributes to search with.
-
discord.utils.
snowflake_time
(id)¶ -
Returns the creation date in UTC of a discord id.
-
discord.utils.
oauth_url
(client_id, permissions=None, server=None, redirect_uri=None)¶ -
A helper function that returns the OAuth2 URL for inviting the bot
into servers.Parameters: - client_id (str) – The client ID for your bot.
- permissions (
Permissions
) – The permissions you’re requesting. If not given then you won’t be requesting any
permissions. - server (
Server
) – The server to pre-select in the authorization screen, if available. - redirect_uri (str) – An optional valid redirect URI.
Application Info¶
-
class
discord.
AppInfo
¶ -
A namedtuple representing the bot’s application info.
-
id
¶ -
The application’s
client_id
.
-
name
¶ -
The application’s name.
-
description
¶ -
The application’s description
-
icon
¶ -
The application’s icon hash if it exists,
None
otherwise.
-
icon_url
¶ -
A property that retrieves the application’s icon URL if it exists.
If it doesn’t exist an empty string is returned.
-
owner
¶ -
The owner of the application. This is a
User
instance
with the owner’s information at the time of the call.
-
Enumerations¶
The API provides some enumerations for certain types of strings to avoid the API
from being stringly typed in case the strings change in the future.
All enumerations are subclasses of enum.
-
class
discord.
ChannelType
¶ -
Specifies the type of
Channel
.-
text
¶ -
A text channel.
-
voice
¶ -
A voice channel.
-
private
¶ -
A private text channel. Also called a direct message.
-
group
¶ -
A private group text channel.
-
category
¶ -
A server category channel.
-
-
class
discord.
MessageType
¶ -
Specifies the type of
Message
. This is used to denote if a message
is to be interpreted as a system message or a regular message.-
default
¶ -
The default message type. This is the same as regular messages.
-
recipient_add
¶ -
The system message when a recipient is added to a group private
message, i.e. a private channel of typeChannelType.group
.
-
recipient_remove
¶ -
The system message when a recipient is removed from a group private
message, i.e. a private channel of typeChannelType.group
.
-
call
¶ -
The system message denoting call state, e.g. missed call, started call,
etc.
-
channel_name_change
¶ -
The system message denoting that a channel’s name has been changed.
-
channel_icon_change
¶ -
The system message denoting that a channel’s icon has been changed.
-
pins_add
¶ -
The system message denoting that a pinned message has been added to a channel.
-
-
class
discord.
ServerRegion
¶ -
Specifies the region a
Server
’s voice server belongs to.-
us_west
¶ -
The US West region.
-
us_east
¶ -
The US East region.
-
us_central
¶ -
The US Central region.
-
eu_west
¶ -
The EU West region.
-
eu_central
¶ -
The EU Central region.
-
singapore
¶ -
The Singapore region.
-
london
¶ -
The London region.
-
sydney
¶ -
The Sydney region.
-
amsterdam
¶ -
The Amsterdam region.
-
frankfurt
¶ -
The Frankfurt region.
-
brazil
¶ -
The Brazil region.
-
vip_us_east
¶ -
The US East region for VIP servers.
-
vip_us_west
¶ -
The US West region for VIP servers.
-
vip_amsterdam
¶ -
The Amsterdam region for VIP servers.
-
-
class
discord.
VerificationLevel
¶ -
Specifies a
Server
’s verification level, which is the criteria in
which a member must meet before being able to send messages to the server.-
none
¶ -
No criteria set.
-
low
¶ -
Member must have a verified email on their Discord account.
-
medium
¶ -
Member must have a verified email and be registered on Discord for more
than five minutes.
-
high
¶ -
Member must have a verified email, be registered on Discord for more
than five minutes, and be a member of the server itself for more than
ten minutes.
-
table_flip
¶ -
An alias for
high
.
-
-
class
discord.
Status
¶ -
Specifies a
Member
‘s status.-
online
¶ -
The member is online.
-
offline
¶ -
The member is offline.
-
idle
¶ -
The member is idle.
-
dnd
¶ -
The member is “Do Not Disturb”.
-
do_not_disturb
¶ -
An alias for
dnd
.
-
invisible
¶ -
The member is “invisible”. In reality, this is only used in sending
a presence a laClient.change_presence()
. When you receive a
user’s presence this will beoffline
instead.
-
Data Classes¶
Some classes are just there to be data containers, this lists them.
Note
With the exception of Object
, Colour
, and Permissions
the
data classes listed below are not intended to be created by users and are also
read-only.
For example, this means that you should not make your own User
instances
nor should you modify the User
instance yourself.
If you want to get one of these data classes instances they’d have to be through
the cache, and a common way of doing so is through the utils.find()
function
or attributes of data classes that you receive from the events specified in the
Event Reference.
Warning
Nearly all data classes here have __slots__
defined which means that it is
impossible to have dynamic attributes to the data classes. The only exception
to this rule is Object
which was designed with dynamic attributes in
mind.
More information about __slots__
can be found
in the official python documentation.
Object¶
-
class
discord.
Object
(id)¶ -
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’
versions of data classes if you want to pass in just an ID. Most functions
that take in a specific data class with an ID can also take in this class
as a substitute instead. Note that even though this is the case, not all
objects (if any) actually inherit from this class.There are also some cases where some websocket events are received
in strange order and when such events happened you would
receive this class rather than the actual data class. These cases are
extremely rare.-
id
¶ -
str – The ID of the object.
-
created_at
¶ -
Returns the snowflake’s creation time in UTC.
-
User¶
-
class
discord.
User
¶ -
Represents a Discord user.
Supported Operations:
Operation Description x == y Checks if two users are equal. x != y Checks if two users are not equal. hash(x) Return the user’s hash. str(x) Returns the user’s name with discriminator. -
name
¶ -
str – The user’s username.
-
id
¶ -
str – The user’s unique ID.
-
discriminator
¶ -
str or int – The user’s discriminator. This is given when the username has conflicts.
-
avatar
¶ -
str – The avatar hash the user has. Could be None.
-
bot
¶ -
bool – Specifies if the user is a bot account.
-
avatar_url
¶ -
Returns a friendly URL version of the avatar variable the user has. An empty string if
the user has no avatar.
-
default_avatar
¶ -
Returns the default avatar for a given user. This is calculated by the user’s descriminator
-
default_avatar_url
¶ -
Returns a URL for a user’s default avatar.
-
mention
¶ -
Returns a string that allows you to mention the given user.
-
permissions_in
(channel)¶ -
An alias for
Channel.permissions_for()
.Basically equivalent to:
channel.permissions_for(self)
Parameters: channel – The channel to check your permissions for.
-
created_at
¶ -
Returns the user’s creation time in UTC.
This is when the user’s discord account was created.
-
display_name
¶ -
Returns the user’s display name.
For regular users this is just their username, but
if they have a server specific nickname then that
is returned instead.
-
mentioned_in
(message)¶ -
Checks if the user is mentioned in the specified message.
Parameters: message ( Message
) – The message to check if you’re mentioned in.
-
Message¶
-
class
discord.
Message
¶ -
Represents a message from Discord.
There should be no need to create one of these manually.
-
edited_timestamp
¶ -
Optional[datetime.datetime] – A naive UTC datetime object containing the edited time of the message.
-
timestamp
¶ -
datetime.datetime – A naive UTC datetime object containing the time the message was created.
-
tts
¶ -
bool – Specifies if the message was done with text-to-speech.
-
type
¶ -
MessageType
– The type of message. In most cases this should not be checked, but it is helpful
in cases where it might be a system message forsystem_content
.
-
A
Member
that sent the message. Ifchannel
is a
private channel, then it is aUser
instead.
-
content
¶ -
str – The actual contents of the message.
-
nonce
¶ -
The value used by the discord server and the client to verify that the message is successfully sent.
This is typically non-important.
-
embeds
¶ -
list – A list of embedded objects. The elements are objects that meet oEmbed’s specification.
-
channel
¶ -
The
Channel
that the message was sent from.
Could be aPrivateChannel
if it’s a private message.
In very rare cases this could be aObject
instead.For the sake of convenience, this
Object
instance has an attributeis_private
set toTrue
.
-
server
¶ -
Optional[
Server
] – The server that the message belongs to. If not applicable (i.e. a PM) then it’s None instead.
-
call
¶ -
Optional[
CallMessage
] – The call that the message refers to. This is only applicable to messages of type
MessageType.call
.
-
mention_everyone
¶ -
bool – Specifies if the message mentions everyone.
Note
This does not check if the
@everyone
text is in the message itself.
Rather this boolean indicates if the@everyone
text is in the message
and it did end up mentioning everyone.
-
mentions
¶ -
list – A list of
Member
that were mentioned. If the message is in a private message
then the list will be ofUser
instead. For messages that are not of type
MessageType.default
, this array can be used to aid in system messages.
For more information, seesystem_content
.Warning
The order of the mentions list is not in any particular order so you should
not rely on it. This is a discord limitation, not one with the library.
-
channel_mentions
¶ -
list – A list of
Channel
that were mentioned. If the message is in a private message
then the list is always empty.
-
role_mentions
¶ -
list – A list of
Role
that were mentioned. If the message is in a private message
then the list is always empty.
-
id
¶ -
str – The message ID.
-
attachments
¶ -
list – A list of attachments given to a message.
-
pinned
¶ -
bool – Specifies if the message is currently pinned.
-
reactions
¶ -
List[
Reaction
] – Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
-
raw_mentions
¶ -
A property that returns an array of user IDs matched with
the syntax of <@user_id> in the message content.This allows you receive the user IDs of mentioned users
even in a private message context.
-
raw_channel_mentions
¶ -
A property that returns an array of channel IDs matched with
the syntax of <#channel_id> in the message content.
-
raw_role_mentions
¶ -
A property that returns an array of role IDs matched with
the syntax of <@&role_id> in the message content.
-
clean_content
¶ -
A property that returns the content in a “cleaned up”
manner. This basically means that mentions are transformed
into the way the client shows it. e.g.<#id>
will transform
into#name
.This will also transform @everyone and @here mentions into
non-mentions.
-
system_content
¶ -
A property that returns the content that is rendered
regardless of theMessage.type
.In the case of
MessageType.default
, this just returns the
regularMessage.content
. Otherwise this returns an English
message denoting the contents of the system message.
-
Reaction¶
-
class
discord.
Reaction
¶ -
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can
have a value ofNone
.Similar to members, the same reaction to a different message are equal.
Supported Operations:
Operation Description x == y Checks if two reactions are the same. x != y Checks if two reactions are not the same. hash(x) Return the emoji’s hash. -
emoji
¶ -
Emoji
or str – The reaction emoji. May be a custom emoji, or a unicode emoji.
-
custom_emoji
¶ -
bool – If this is a custom emoji.
-
count
¶ -
int – Number of times this reaction was made
-
me
¶ -
bool – If the user sent this reaction.
-
message
¶ -
Message
– Message this reaction is for.
-
Embed¶
-
class
discord.
Embed
(**kwargs)¶ -
Represents a Discord embed.
The following attributes can be set during creation
of the object:Certain properties return an
EmbedProxy
. Which is a type
that acts similar to a regular dict except access the attributes
via dotted access, e.g.embed.author.icon_url
. If the attribute
is invalid or empty, then a special sentinel value is returned,
Embed.Empty
.For ease of use, all parameters that expect a
str
are implicitly
casted tostr
for you.-
title
¶ -
str – The title of the embed.
-
type
¶ -
str – The type of embed. Usually “rich”.
-
description
¶ -
str – The description of the embed.
-
url
¶ -
str – The URL of the embed.
-
timestamp
¶ -
datetime.datetime – The timestamp of the embed content.
-
colour
¶ -
Colour
or int – The colour code of the embed. Aliased tocolor
as well.
-
Empty
¶ -
A special sentinel value used by
EmbedProxy
and this class
to denote that the value or attribute is empty.
-
Returns a
EmbedProxy
denoting the footer contents.See
set_footer()
for possible values you can access.If the attribute has no value then
Empty
is returned.
-
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style
chaining.Parameters: - text (str) – The footer text.
- icon_url (str) – The URL of the footer icon. Only HTTP(S) is supported.
-
image
¶ -
Returns a
EmbedProxy
denoting the image contents.Possible attributes you can access are:
url
proxy_url
width
height
If the attribute has no value then
Empty
is returned.
-
set_image
(*, url)¶ -
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style
chaining.Parameters: url (str) – The source URL for the image. Only HTTP(S) is supported.
-
thumbnail
¶ -
Returns a
EmbedProxy
denoting the thumbnail contents.Possible attributes you can access are:
url
proxy_url
width
height
If the attribute has no value then
Empty
is returned.
-
set_thumbnail
(*, url)¶ -
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style
chaining.Parameters: url (str) – The source URL for the thumbnail. Only HTTP(S) is supported.
-
video
¶ -
Returns a
EmbedProxy
denoting the video contents.Possible attributes include:
url
for the video URL.height
for the video height.width
for the video width.
If the attribute has no value then
Empty
is returned.
-
provider
¶ -
Returns a
EmbedProxy
denoting the provider contents.The only attributes that might be accessed are
name
andurl
.If the attribute has no value then
Empty
is returned.
-
author
¶ -
Returns a
EmbedProxy
denoting the author contents.See
set_author()
for possible values you can access.If the attribute has no value then
Empty
is returned.
-
set_author
(*, name, url=Embed.Empty, icon_url=Embed.Empty)¶ -
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style
chaining.Parameters: - name (str) – The name of the author.
- url (str) – The URL for the author.
- icon_url (str) – The URL of the author icon. Only HTTP(S) is supported.
-
fields
¶ -
Returns a list of
EmbedProxy
denoting the field contents.See
add_field()
for possible values you can access.If the attribute has no value then
Empty
is returned.
-
add_field
(*, name, value, inline=True)¶ -
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style
chaining.Parameters: - name (str) – The name of the field.
- value (str) – The value of the field.
- inline (bool) – Whether the field should be displayed inline.
-
clear_fields
()¶ -
Removes all fields from this embed.
-
remove_field
(index)¶ -
Removes a field at a specified index.
If the index is invalid or out of bounds then the error is
silently swallowed.Note
When deleting a field by index, the index of the other fields
shift to fill the gap just like a regular list.Parameters: index (int) – The index of the field to remove.
-
set_field_at
(index, *, name, value, inline=True)¶ -
Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style
chaining.Parameters: - index (int) – The index of the field to modify.
- name (str) – The name of the field.
- value (str) – The value of the field.
- inline (bool) – Whether the field should be displayed inline.
Raises: IndexError
– An invalid index was provided.
-
to_dict
()¶ -
Converts this embed object into a dict.
-
CallMessage¶
-
class
discord.
CallMessage
¶ -
Represents a group call message from Discord.
This is only received in cases where the message type is equivalent to
MessageType.call
.-
ended_timestamp
¶ -
Optional[datetime.datetime] – A naive UTC datetime object that represents the time that the call has ended.
-
participants
¶ -
List[
User
] – The list of users that are participating in this call.
-
message
¶ -
Message
– The message associated with this call message.
-
call_ended
¶ -
bool – Indicates if the call has ended.
-
channel
¶ -
PrivateChannel
– The private channel associated with this message.
-
duration
¶ -
Queries the duration of the call.
If the call has not ended then the current duration will
be returned.Returns: The timedelta object representing the duration. Return type: datetime.timedelta
-
GroupCall¶
-
class
discord.
GroupCall
¶ -
Represents the actual group call from Discord.
This is accompanied with a
CallMessage
denoting the information.-
call
¶ -
CallMessage
– The call message associated with this group call.
-
unavailable
¶ -
bool – Denotes if this group call is unavailable.
-
ringing
¶ -
List[
User
] – A list of users that are currently being rung to join the call.
-
region
¶ -
ServerRegion
– The server region the group call is being hosted on.
-
connected
¶ -
A property that returns the list of
User
that are currently in this call.
-
channel
¶ -
PrivateChannel
– Returns the channel the group call is in.
-
voice_state_for
(user)¶ -
Retrieves the
VoiceState
for a specifiedUser
.If the
User
has no voice state then this function returns
None
.Parameters: user ( User
) – The user to retrieve the voice state for.Returns: The voice state associated with this user. Return type: Optiona[ VoiceState
]
-
Server¶
-
class
discord.
Server
¶ -
Represents a Discord server.
Supported Operations:
Operation Description x == y Checks if two servers are equal. x != y Checks if two servers are not equal. hash(x) Returns the server’s hash. str(x) Returns the server’s name. -
name
¶ -
str – The server name.
-
me
¶ -
Member
– Similar toClient.user
except an instance ofMember
.
This is essentially used to get the member version of yourself.
-
roles
¶ -
A list of
Role
that the server has available.
-
emojis
¶ -
A list of
Emoji
that the server owns.
-
region
¶ -
ServerRegion
– The region the server belongs on. There is a chance that the region
will be astr
if the value is not recognised by the enumerator.
-
afk_timeout
¶ -
int – The timeout to get sent to the AFK channel.
-
afk_channel
¶ -
Channel
– The channel that denotes the AFK channel. None if it doesn’t exist.
-
members
¶ -
An iterable of
Member
that are currently on the server.
-
channels
¶ -
An iterable of
Channel
that are currently on the server.
-
icon
¶ -
str – The server’s icon.
-
id
¶ -
str – The server’s ID.
-
owner
¶ -
Member
– The member who owns the server.
-
unavailable
¶ -
bool – Indicates if the server is unavailable. If this is
True
then the
reliability of other attributes outside ofServer.id()
is slim and they might
all be None. It is best to not do anything with the server if it is unavailable.Check the
on_server_unavailable()
andon_server_available()
events.
-
large
¶ -
bool – Indicates if the server is a ‘large’ server. A large server is defined as having
more thanlarge_threshold
count members, which for this library is set to
the maximum of 250.
-
voice_client
¶ -
Optional[
VoiceClient
] – The VoiceClient associated with this server. A shortcut for the
Client.voice_client_in()
call.
-
mfa_level
¶ -
int – Indicates the server’s two factor authorisation level. If this value is 0 then
the server does not require 2FA for their administrative members. If the value is
1 then they do.
-
verification_level
¶ -
VerificationLevel
– The server’s verification level.
-
features
¶ -
List[str] – A list of features that the server has. They are currently as follows:
VIP_REGIONS
: Server has VIP voice regionsVANITY_URL
: Server has a vanity invite URL (e.g. discord.gg/discord-api)INVITE_SPLASH
: Server’s invite page has a special splash.
-
splash
¶ -
str – The server’s invite splash.
-
get_channel
(channel_id)¶ -
Returns a
Channel
with the given ID. If not found, returns None.
-
get_member
(user_id)¶ -
Returns a
Member
with the given ID. If not found, returns None.
-
default_role
¶ -
Gets the @everyone role that all members have by default.
-
default_channel
¶ -
Gets the default
Channel
for the server.
-
icon_url
¶ -
Returns the URL version of the server’s icon. Returns an empty string if it has no icon.
-
splash_url
¶ -
Returns the URL version of the server’s invite splash. Returns an empty string if it has no splash.
-
member_count
¶ -
Returns the true member count regardless of it being loaded fully or not.
-
created_at
¶ -
Returns the server’s creation time in UTC.
-
role_hierarchy
¶ -
Returns the server’s roles in the order of the hierarchy.
The first element of this list will be the highest role in the
hierarchy.
-
get_member_named
(name)¶ -
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001”
or “Jake” will both do the lookup. However the former will give a more
precise result. Note that the discriminator must have all 4 digits
for this to work.If a nickname is passed, then it is looked up via the nickname. Note
however, that a nickname + discriminator combo will not lookup the nickname
but rather the username + discriminator combo due to nickname + discriminator
not being unique.If no member is found,
None
is returned.Parameters: name (str) – The name of the member to lookup with an optional discriminator. Returns: The member in this server with the associated name. If not found
thenNone
is returned.Return type: Member
-
Member¶
-
class
discord.
Member
¶ -
Represents a Discord member to a
Server
.This is a subclass of
User
that extends more functionality
that server members have such as roles and permissions.-
voice
¶ -
VoiceState
– The member’s voice state. Properties are defined to mirror access of the attributes.
e.g.Member.is_afk
is equivalent to Member.voice.is_afk`.
-
roles
¶ -
A list of
Role
that the member belongs to. Note that the first element of this
list is always the default ‘@everyone’ role.
-
joined_at
¶ -
datetime.datetime – A datetime object that specifies the date and time in UTC that the member joined the server for
the first time.
-
status
¶ -
Status
– The member’s status. There is a chance that the status will be astr
if it is a value that is not recognised by the enumerator.
-
game
¶ -
Game
– The game that the user is currently playing. Could be None if no game is being played.
-
server
¶ -
Server
– The server that the member belongs to.
-
nick
¶ -
Optional[str] – The server specific nickname of the user.
-
colour
¶ -
A property that returns a
Colour
denoting the rendered colour
for the member. If the default colour is the one rendered then an instance
ofColour.default()
is returned.There is an alias for this under
color
.
-
color
¶ -
A property that returns a
Colour
denoting the rendered colour
for the member. If the default colour is the one rendered then an instance
ofColour.default()
is returned.There is an alias for this under
color
.
-
top_role
¶ -
Returns the member’s highest role.
This is useful for figuring where a member stands in the role
hierarchy chain.
-
server_permissions
¶ -
Returns the member’s server permissions.
This only takes into consideration the server permissions
and not most of the implied permissions or any of the
channel permission overwrites. For 100% accurate permission
calculation, please use eitherpermissions_in()
or
Channel.permissions_for()
.This does take into consideration server ownership and the
administrator implication.
-
VoiceState¶
-
class
discord.
VoiceState
¶ -
Represents a Discord user’s voice state.
-
deaf
¶ -
bool – Indicates if the user is currently deafened by the server.
-
mute
¶ -
bool – Indicates if the user is currently muted by the server.
-
self_mute
¶ -
bool – Indicates if the user is currently muted by their own accord.
-
self_deaf
¶ -
bool – Indicates if the user is currently deafened by their own accord.
-
is_afk
¶ -
bool – Indicates if the user is currently in the AFK channel in the server.
-
voice_channel
¶ -
Optional[Union[
Channel
,PrivateChannel
]] – The voice channel that the user is currently connected to. None if the user
is not currently in a voice channel.
-
Colour¶
-
class
discord.
Colour
(value)¶ -
Represents a Discord role colour. This class is similar
to an (red, green, blue) tuple.There is an alias for this called Color.
Supported operations:
Operation Description x == y Checks if two colours are equal. x != y Checks if two colours are not equal. hash(x) Return the colour’s hash. str(x) Returns the hex format for the colour. -
value
¶ -
int – The raw integer colour value.
-
r
¶ -
Returns the red component of the colour.
-
g
¶ -
Returns the green component of the colour.
-
b
¶ -
Returns the blue component of the colour.
-
to_tuple
()¶ -
Returns an (r, g, b) tuple representing the colour.
-
classmethod
default
()¶ -
A factory method that returns a
Colour
with a value of 0.
-
classmethod
teal
()¶ -
A factory method that returns a
Colour
with a value of0x1abc9c
.
-
classmethod
dark_teal
()¶ -
A factory method that returns a
Colour
with a value of0x11806a
.
-
classmethod
green
()¶ -
A factory method that returns a
Colour
with a value of0x2ecc71
.
-
classmethod
dark_green
()¶ -
A factory method that returns a
Colour
with a value of0x1f8b4c
.
-
classmethod
blue
()¶ -
A factory method that returns a
Colour
with a value of0x3498db
.
-
classmethod
dark_blue
()¶ -
A factory method that returns a
Colour
with a value of0x206694
.
-
classmethod
purple
()¶ -
A factory method that returns a
Colour
with a value of0x9b59b6
.
-
classmethod
dark_purple
()¶ -
A factory method that returns a
Colour
with a value of0x71368a
.
-
classmethod
magenta
()¶ -
A factory method that returns a
Colour
with a value of0xe91e63
.
-
classmethod
dark_magenta
()¶ -
A factory method that returns a
Colour
with a value of0xad1457
.
-
classmethod
gold
()¶ -
A factory method that returns a
Colour
with a value of0xf1c40f
.
-
classmethod
dark_gold
()¶ -
A factory method that returns a
Colour
with a value of0xc27c0e
.
-
classmethod
orange
()¶ -
A factory method that returns a
Colour
with a value of0xe67e22
.
-
classmethod
dark_orange
()¶ -
A factory method that returns a
Colour
with a value of0xa84300
.
-
classmethod
red
()¶ -
A factory method that returns a
Colour
with a value of0xe74c3c
.
-
classmethod
dark_red
()¶ -
A factory method that returns a
Colour
with a value of0x992d22
.
-
classmethod
lighter_grey
()¶ -
A factory method that returns a
Colour
with a value of0x95a5a6
.
-
classmethod
dark_grey
()¶ -
A factory method that returns a
Colour
with a value of0x607d8b
.
-
classmethod
light_grey
()¶ -
A factory method that returns a
Colour
with a value of0x979c9f
.
-
classmethod
darker_grey
()¶ -
A factory method that returns a
Colour
with a value of0x546e7a
.
-
Game¶
-
class
discord.
Game
(**kwargs)¶ -
Represents a Discord game.
Supported Operations:
Operation Description x == y Checks if two games are equal. x != y Checks if two games are not equal. hash(x) Return the games’s hash. str(x) Returns the games’s name. -
name
¶ -
str – The game’s name.
-
url
¶ -
str – The game’s URL. Usually used for twitch streaming.
-
type
¶ -
int – The type of game being played. 1 indicates “Streaming”.
-
Emoji¶
-
class
discord.
Emoji
¶ -
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can
have a value ofNone
.Supported Operations:
Operation Description x == y Checks if two emoji are the same. x != y Checks if two emoji are not the same. hash(x) Return the emoji’s hash. iter(x) Returns an iterator of (field, value)
pairs. This allows this class to be
used as an iterable in list/dict/etc.
constructions.str(x) Returns the emoji rendered for discord. -
name
¶ -
str – The name of the emoji.
-
id
¶ -
str – The emoji’s ID.
-
require_colons
¶ -
bool – If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
-
managed
¶ -
bool – If this emoji is managed by a Twitch integration.
-
server
¶ -
Server
– The server the emoji belongs to.
-
roles
¶ -
List[
Role
] – A list ofRole
that is allowed to use this emoji. If roles is empty,
the emoji is unrestricted.
-
created_at
¶ -
Returns the emoji’s creation time in UTC.
-
url
¶ -
Returns a URL version of the emoji.
-
Role¶
-
class
discord.
Role
¶ -
Represents a Discord role in a
Server
.Supported Operations:
Operation Description x == y Checks if two roles are equal. x != y Checks if two roles are not equal. x > y Checks if a role is higher than another in the hierarchy. x < y Checks if a role is lower than another in the hierarchy. x >= y Checks if a role is higher or equal to another in the hierarchy. x <= y Checks if a role is lower or equal to another in the hierarchy. hash(x) Return the role’s hash. str(x) Returns the role’s name. -
id
¶ -
str – The ID for the role.
-
name
¶ -
str – The name of the role.
-
permissions
¶ -
Permissions
– Represents the role’s permissions.
-
server
¶ -
Server
– The server the role belongs to.
-
colour
¶ -
Colour
– Represents the role colour. An alias exists undercolor
.
-
hoist
¶ -
bool – Indicates if the role will be displayed separately from other members.
-
position
¶ -
int – The position of the role. This number is usually positive. The bottom
role has a position of 0.
-
managed
¶ -
bool – Indicates if the role is managed by the server through some form of
integrations such as Twitch.
-
mentionable
¶ -
bool – Indicates if the role can be mentioned by users.
-
is_everyone
¶ -
Checks if the role is the @everyone role.
-
created_at
¶ -
Returns the role’s creation time in UTC.
-
mention
¶ -
Returns a string that allows you to mention a role.
-
Permissions¶
-
class
discord.
Permissions
(permissions=0, **kwargs)¶ -
Wraps up the Discord permission value.
Supported operations:
Operation Description x == y Checks if two permissions are equal. x != y Checks if two permissions are not equal. x <= y Checks if a permission is a subset
of another permission.x >= y Checks if a permission is a superset
of another permission.x < y Checks if a permission is a strict
subset of another permission.x > y Checks if a permission is a strict
superset of another permission.hash(x) Return the permission’s hash. iter(x) Returns an iterator of (perm, value)
pairs. This allows this class to be used
as an iterable in e.g. set/list/dict
constructions.The properties provided are two way. You can set and retrieve individual bits using the properties as if they
were regular bools. This allows you to edit permissions.-
value
¶ -
The raw value. This value is a bit array field of a 32-bit integer
representing the currently available permissions. You should query
permissions via the properties rather than using this raw value.
-
is_subset
(other)¶ -
Returns True if self has the same or fewer permissions as other.
-
is_superset
(other)¶ -
Returns True if self has the same or more permissions as other.
-
is_strict_subset
(other)¶ -
Returns True if the permissions on other are a strict subset of those on self.
-
is_strict_superset
(other)¶ -
Returns True if the permissions on other are a strict superset of those on self.
-
classmethod
none
()¶ -
A factory method that creates a
Permissions
with all
permissions set to False.
-
classmethod
all
()¶ -
A factory method that creates a
Permissions
with all
permissions set to True.
-
classmethod
all_channel
()¶ -
A
Permissions
with all channel-specific permissions set to
True and the server-specific ones set to False. The server-specific
permissions are currently:- manager_server
- kick_members
- ban_members
- administrator
- change_nicknames
- manage_nicknames
-
classmethod
general
()¶ -
A factory method that creates a
Permissions
with all
“General” permissions from the official Discord UI set to True.
-
classmethod
text
()¶ -
A factory method that creates a
Permissions
with all
“Text” permissions from the official Discord UI set to True.
-
classmethod
voice
()¶ -
A factory method that creates a
Permissions
with all
“Voice” permissions from the official Discord UI set to True.
-
update
(**kwargs)¶ -
Bulk updates this permission object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.Parameters: **kwargs – A list of key/value pairs to bulk update permissions with.
-
create_instant_invite
¶ -
Returns True if the user can create instant invites.
-
kick_members
¶ -
Returns True if the user can kick users from the server.
-
ban_members
¶ -
Returns True if a user can ban users from the server.
-
administrator
¶ -
Returns True if a user is an administrator. This role overrides all other permissions.
This also bypasses all channel-specific overrides.
-
manage_channels
¶ -
Returns True if a user can edit, delete, or create channels in the server.
This also corresponds to the “manage channel” channel-specific override.
-
manage_server
¶ -
Returns True if a user can edit server properties.
-
add_reactions
¶ -
Returns True if a user can add reactions to messages.
-
view_audit_logs
¶ -
Returns True if a user can view the server’s audit log.
-
read_messages
¶ -
Returns True if a user can read messages from all or specific text channels.
-
send_messages
¶ -
Returns True if a user can send messages from all or specific text channels.
-
send_tts_messages
¶ -
Returns True if a user can send TTS messages from all or specific text channels.
-
manage_messages
¶ -
Returns True if a user can delete messages from a text channel. Note that there are currently no ways to edit other people’s messages.
-
embed_links
¶ -
Returns True if a user’s messages will automatically be embedded by Discord.
-
attach_files
¶ -
Returns True if a user can send files in their messages.
-
read_message_history
¶ -
Returns True if a user can read a text channel’s previous messages.
-
mention_everyone
¶ -
Returns True if a user’s @everyone will mention everyone in the text channel.
-
external_emojis
¶ -
Returns True if a user can use emojis from other servers.
-
connect
¶ -
Returns True if a user can connect to a voice channel.
-
speak
¶ -
Returns True if a user can speak in a voice channel.
-
mute_members
¶ -
Returns True if a user can mute other users.
-
deafen_members
¶ -
Returns True if a user can deafen other users.
-
move_members
¶ -
Returns True if a user can move users between other voice channels.
-
use_voice_activation
¶ -
Returns True if a user can use voice activation in voice channels.
-
change_nickname
¶ -
Returns True if a user can change their nickname in the server.
-
manage_nicknames
¶ -
Returns True if a user can change other user’s nickname in the server.
-
manage_roles
¶ -
Returns True if a user can create or edit roles less than their role’s position.
This also corresponds to the “manage permissions” channel-specific override.
-
manage_webhooks
¶ -
Returns True if a user can create, edit, or delete webhooks.
-
manage_emojis
¶ -
Returns True if a user can create, edit, or delete emojis.
-
PermissionOverwrite¶
-
class
discord.
PermissionOverwrite
(**kwargs)¶ -
A type that is used to represent a channel specific permission.
Unlike a regular
Permissions
, the default value of a
permission is equivalent toNone
and notFalse
. Setting
a value toFalse
is explicitly denying that permission,
while setting a value toTrue
is explicitly allowing
that permission.The values supported by this are the same as
Permissions
with the added possibility of it being set toNone
.Supported operations:
Operation Description iter(x) Returns an iterator of (perm, value)
pairs. This allows this class to be used
as an iterable in e.g. set/list/dict
constructions.Parameters: **kwargs – Set the value of permissions by their name. -
pair
()¶ -
Returns the (allow, deny) pair from this overwrite.
The value of these pairs is
Permissions
.
-
classmethod
from_pair
(allow, deny)¶ -
Creates an overwrite from an allow/deny pair of
Permissions
.
-
is_empty
()¶ -
Checks if the permission overwrite is currently empty.
An empty permission overwrite is one that has no overwrites set
to True or False.
-
update
(**kwargs)¶ -
Bulk updates this permission overwrite object.
Allows you to set multiple attributes by using keyword
arguments. The names must be equivalent to the properties
listed. Extraneous key/value pairs will be silently ignored.Parameters: **kwargs – A list of key/value pairs to bulk update with.
-
Channel¶
-
class
discord.
Channel
¶ -
Represents a Discord server channel.
Supported Operations:
Operation Description x == y Checks if two channels are equal. x != y Checks if two channels are not equal. hash(x) Returns the channel’s hash. str(x) Returns the channel’s name. -
name
¶ -
str – The channel name.
-
server
¶ -
Server
– The server the channel belongs to.
-
id
¶ -
str – The channel ID.
-
topic
¶ -
Optional[str] – The channel’s topic. None if it doesn’t exist.
-
is_private
¶ -
bool –
True
if the channel is a private channel (i.e. PM).False
in this case.
-
position
¶ -
int – The position in the channel list. This is a number that starts at 0. e.g. the
top channel is position 0. The position varies depending on being a voice channel
or a text channel, so a 0 position voice channel is on top of the voice channel
list.
-
type
¶ -
ChannelType
– The channel type. There is a chance that the type will bestr
if
the channel type is not within the ones recognised by the enumerator.
-
bitrate
¶ -
int – The channel’s preferred audio bitrate in bits per second.
-
voice_members
¶ -
A list of
Members
that are currently inside this voice channel.
Iftype
is notChannelType.voice
then this is always an empty array.
-
user_limit
¶ -
int – The channel’s limit for number of members that can be in a voice channel.
-
changed_roles
¶ -
Returns a list of
Roles
that have been overridden from
their default values in theServer.roles
attribute.
-
is_default
¶ -
bool – Indicates if this is the default channel for the
Server
it belongs to.
-
mention
¶ -
str – The string that allows you to mention the channel.
-
created_at
¶ -
Returns the channel’s creation time in UTC.
-
overwrites_for
(obj)¶ -
Returns the channel-specific overwrites for a member or a role.
Parameters: obj – The Role
orMember
orObject
denoting
whose overwrite to get.Returns: The permission overwrites for this object. Return type: PermissionOverwrite
-
overwrites
¶ -
Returns all of the channel’s overwrites.
This is returned as a list of two-element tuples containing the target,
which can be either aRole
or aMember
and the overwrite
as the second element as aPermissionOverwrite
.Returns: The channel’s permission overwrites. Return type: List[Tuple[Union[ Role
,Member
],PermissionOverwrite
]]
-
permissions_for
(member)¶ -
Handles permission resolution for the current
Member
.This function takes into consideration the following cases:
- Server owner
- Server roles
- Channel overrides
- Member overrides
- Whether the channel is the default channel.
Parameters: member ( Member
) – The member to resolve permissions for.Returns: The resolved permissions for the member. Return type: Permissions
-
PrivateChannel¶
-
class
discord.
PrivateChannel
¶ -
Represents a Discord private channel.
Supported Operations:
Operation Description x == y Checks if two channels are equal. x != y Checks if two channels are not equal. hash(x) Returns the channel’s hash. str(x) Returns a string representation of the channel -
recipients
¶ -
list of
User
– The users you are participating with in the private channel.
-
me
¶ -
User
– The user presenting yourself.
-
id
¶ -
str – The private channel ID.
-
is_private
¶ -
bool –
True
if the channel is a private channel (i.e. PM).True
in this case.
-
type
¶ -
ChannelType
– The type of private channel.
-
owner
¶ -
Optional[
User
] – The user that owns the private channel. If the channel type is not
ChannelType.group
then this is alwaysNone
.
-
icon
¶ -
Optional[str] – The private channel’s icon hash. If the channel type is not
ChannelType.group
then this is alwaysNone
.
-
name
¶ -
Optional[str] – The private channel’s name. If the channel type is not
ChannelType.group
then this is alwaysNone
.
-
user
¶ -
A property that returns the first recipient of the private channel.
This is mainly for compatibility and ease of use with old style private
channels that had a single recipient.
-
icon_url
¶ -
Returns the channel’s icon URL if available or an empty string otherwise.
-
created_at
¶ -
Returns the private channel’s creation time in UTC.
-
permissions_for
(user)¶ -
Handles permission resolution for a
User
.This function is there for compatibility with
Channel
.Actual private messages do not really have the concept of permissions.
This returns all the Text related permissions set to true except:
- send_tts_messages: You cannot send TTS messages in a PM.
- manage_messages: You cannot delete others messages in a PM.
This also handles permissions for
ChannelType.group
channels
such as kicking or mentioning everyone.Parameters: user ( User
) – The user to check permissions for.Returns: The resolved permissions for the user. Return type: Permissions
-
Invite¶
-
class
discord.
Invite
¶ -
Represents a Discord
Server
orChannel
invite.Depending on the way this object was created, some of the attributes can
have a value ofNone
.Supported Operations:
Operation Description x == y Checks if two invites are equal. x != y Checks if two invites are not equal. hash(x) Return the invite’s hash. str(x) Returns the invite’s URL. -
max_age
¶ -
int – How long the before the invite expires in seconds. A value of 0 indicates that it doesn’t expire.
-
code
¶ -
str – The URL fragment used for the invite.
xkcd
is also a possible fragment.
-
server
¶ -
Server
– The server the invite is for.
-
revoked
¶ -
bool – Indicates if the invite has been revoked.
-
created_at
¶ -
datetime.datetime – A datetime object denoting the time the invite was created.
-
temporary
¶ -
bool – Indicates that the invite grants temporary membership.
If True, members who joined via this invite will be kicked upon disconnect.
-
uses
¶ -
int – How many times the invite has been used.
-
max_uses
¶ -
int – How many times the invite can be used.
-
xkcd
¶ -
str – The URL fragment used for the invite if it is human readable.
-
inviter
¶ -
User
– The user who created the invite.
-
channel
¶ -
Channel
– The channel the invite is for.
-
id
¶ -
Returns the proper code portion of the invite.
-
url
¶ -
A property that retrieves the invite URL.
-
Exceptions¶
The following exceptions are thrown by the library.
-
exception
discord.
DiscordException
¶ -
Base exception class for discord.py
Ideally speaking, this could be caught to handle any exceptions thrown from this library.
-
exception
discord.
ClientException
¶ -
Exception that’s thrown when an operation in the
Client
fails.These are usually for exceptions that happened due to user input.
-
exception
discord.
LoginFailure
¶ -
Exception that’s thrown when the
Client.login()
function
fails to log you in from improper credentials or some other misc.
failure.
-
exception
discord.
HTTPException
(response, message)¶ -
Exception that’s thrown when an HTTP request operation fails.
-
response
¶ -
The response of the failed HTTP request. This is an
instance of aiohttp.ClientResponse.
-
text
¶ -
The text of the error. Could be an empty string.
-
-
exception
discord.
Forbidden
(response, message)¶ -
Exception that’s thrown for when status code 403 occurs.
Subclass of
HTTPException
-
exception
discord.
NotFound
(response, message)¶ -
Exception that’s thrown for when status code 404 occurs.
Subclass of
HTTPException
-
exception
discord.
InvalidArgument
¶ -
Exception that’s thrown when an argument to a function
is invalid some way (e.g. wrong value or wrong type).This could be considered the analogous of
ValueError
and
TypeError
except derived fromClientException
and thus
DiscordException
.
-
exception
discord.
GatewayNotFound
¶ -
An exception that is usually thrown when the gateway hub
for theClient
websocket is not found.
-
exception
discord.
ConnectionClosed
(original)¶ -
Exception that’s thrown when the gateway connection is
closed for reasons that could not be handled internally.-
code
¶ -
int – The close code of the websocket.
-
reason
¶ -
str – The reason provided for the closure.
-
-
exception
discord.opus.
OpusError
(code)¶ -
An exception that is thrown for libopus related errors.
-
code
¶ -
int – The error code returned.
-
-
exception
discord.opus.
OpusNotLoaded
¶ -
An exception that is thrown for when libopus is not loaded.
this is the code of the eventargs,The problem is the error is this «no overload for ‘_btnadd_click’matches delegate ‘EventHandler’
private void _btnadd_Click (object sender, EventArgs e,DataGridViewCellEventArgs r)
{
foreach (DataGridViewRow row in DataGridView1.Rows)
{
if (row.Cells[0].Value != null)
{
if ((Boolean)row.Cells[0].Value == true)
{
MessageBox.Show("added");
int structureOptionId = int.Parse(DataGridView1.Rows[r.RowIndex].Cells[1].Value.ToString());
AddStructureOptionToLists(structureOptionId);
}
}
}
}
asked Aug 15, 2018 at 0:41
kyleekylee
11 silver badge1 bronze badge
4
O didn’t understand why you need two EventArgs. I mean, you could create a class MyEventArgs : EventArgs
with the properties you need and declare your EventHandler like that:
public event EventHandler<MyEventArgs> MyEventHandler;
Let me know if it helps you.
answered Aug 15, 2018 at 1:02
2