code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
getStickerSet(name, form = {}) {
form.name = name;
return this._request('getStickerSet', { form });
}
|
Use this method to get a sticker set.
@param {String} name Name of the sticker set
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned
@see https://core.telegram.org/bots/api#getstickerset
|
getStickerSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getCustomEmojiStickers(customEmojiIds, form = {}) {
form.custom_emoji_ids = stringify(customEmojiIds);
return this._request('getCustomEmojiStickers', { form });
}
|
Use this method to get information about custom emoji stickers by their identifiers.
@param {Array} custom_emoji_ids List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
@param {Object} [options] Additional Telegram query options
@return {Promise} Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects.
@see https://core.telegram.org/bots/api#getcustomemojistickers
|
getCustomEmojiStickers
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
uploadStickerFile(userId, sticker, stickerFormat = 'static', options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.sticker_format = stickerFormat;
try {
const sendData = this._formatSendData('sticker', sticker, fileOptions);
opts.formData = sendData[0];
opts.qs.sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('uploadStickerFile', opts);
}
|
Use this method to upload a file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
times).
@param {Number} userId User identifier of sticker file owner
@param {String|stream.Stream|Buffer} sticker A file path or a Stream with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. Can also be a `file_id` previously uploaded.
@param {String} stickerFormat Allow values: `static`, `animated` or `video`
@param {Object} [options] Additional Telegram query options
@param {Object} [fileOptions] Optional file related meta-data
@return {Promise} On success, a [File](https://core.telegram.org/bots/api#file) object is returned
@see https://core.telegram.org/bots/api#uploadstickerfile
|
uploadStickerFile
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
createNewStickerSet(userId, name, title, pngSticker, emojis, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.title = title;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
try {
const sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
opts.formData = sendData[0];
opts.qs.png_sticker = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('createNewStickerSet', opts);
}
|
Use this method to create new sticker set owned by a user.
The bot will be able to edit the created sticker set.
You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
@param {Number} userId User identifier of created sticker set owner
@param {String} name Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., *"animals"*). Can contain only english letters, digits and underscores.
Must begin with a letter, can't contain consecutive underscores and must end in `"_by_<bot_username>"`. `<bot_username>` is case insensitive. 1-64 characters.
@param {String} title Sticker set title, 1-64 characters
@param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px.
@param {String} emojis One or more emoji corresponding to the sticker
@param {Object} [options] Additional Telegram query options
@param {Object} [fileOptions] Optional file related meta-data
@return {Promise} True on success
@see https://core.telegram.org/bots/api#createnewstickerset
|
createNewStickerSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
addStickerToSet(userId, name, sticker, emojis, stickerType = 'png_sticker', options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.emojis = emojis;
opts.qs.mask_position = stringify(options.mask_position);
if (typeof stickerType !== 'string' || ['png_sticker', 'tgs_sticker', 'webm_sticker'].indexOf(stickerType) === -1) {
return Promise.reject(new Error('stickerType must be a string and the allow types is: png_sticker, tgs_sticker, webm_sticker'));
}
try {
const sendData = this._formatSendData(stickerType, sticker, fileOptions);
opts.formData = sendData[0];
opts.qs[stickerType] = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('addStickerToSet', opts);
}
|
Use this method to add a new sticker to a set created by the bot.
You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
Animated stickers can be added to animated sticker sets and only to them
Note:
- Emoji sticker sets can have up to 200 sticker
- Static or Animated sticker sets can have up to 120 stickers
@param {Number} userId User identifier of sticker set owner
@param {String} name Sticker set name
@param {String|stream.Stream|Buffer} sticker Png image with the sticker (must be up to 512 kilobytes in size,
dimensions must not exceed 512px, and either width or height must be exactly 512px, [TGS animation](https://core.telegram.org/stickers#animated-sticker-requirements)
with the sticker or [WEBM video](https://core.telegram.org/stickers#video-sticker-requirements) with the sticker.
@param {String} emojis One or more emoji corresponding to the sticker
@param {String} stickerType Allow values: `png_sticker`, `tgs_sticker`, or `webm_sticker`.
@param {Object} [options] Additional Telegram query options
@param {Object} [fileOptions] Optional file related meta-data
@return {Promise} True on success
@see https://core.telegram.org/bots/api#addstickertoset
|
addStickerToSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerPositionInSet(sticker, position, form = {}) {
form.sticker = sticker;
form.position = position;
return this._request('setStickerPositionInSet', { form });
}
|
Use this method to move a sticker in a set created by the bot to a specific position.
@param {String} sticker File identifier of the sticker
@param {Number} position New sticker position in the set, zero-based
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickerpositioninset
|
setStickerPositionInSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
deleteStickerFromSet(sticker, form = {}) {
form.sticker = sticker;
return this._request('deleteStickerFromSet', { form });
}
|
Use this method to delete a sticker from a set created by the bot.
@param {String} sticker File identifier of the sticker
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#deletestickerfromset
@todo Add tests for this method!
|
deleteStickerFromSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
replaceStickerInSet(userId, name, oldSticker, form = {}) {
form.user_id = userId;
form.name = name;
form.old_sticker = oldSticker;
return this._request('deleteStickerFromSet', { form });
}
|
Use this method to replace an existing sticker in a sticker set with a new one
@param {Number} user_id User identifier of the sticker set owner
@param {String} name Sticker set name
@param {String} sticker File identifier of the sticker
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#replacestickerinset
@todo Add tests for this method!
|
replaceStickerInSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerEmojiList(sticker, emojiList, form = {}) {
form.sticker = sticker;
form.emoji_list = stringify(emojiList);
return this._request('setStickerEmojiList', { form });
}
|
Use this method to change the list of emoji assigned to a regular or custom emoji sticker.
The sticker must belong to a sticker set created by the bot.
@param {String} sticker File identifier of the sticker
@param { Array } emojiList A JSON-serialized list of 1-20 emoji associated with the sticker
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickeremojilist
|
setStickerEmojiList
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerKeywords(sticker, form = {}) {
form.sticker = sticker;
if (form.keywords) {
form.keywords = stringify(form.keywords);
}
return this._request('setStickerKeywords', { form });
}
|
Use this method to change the list of emoji assigned to a `regular` or `custom emoji` sticker.
The sticker must belong to a sticker set created by the bot.
@param {String} sticker File identifier of the sticker
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickerkeywords
|
setStickerKeywords
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerMaskPosition(sticker, form = {}) {
form.sticker = sticker;
if (form.mask_position) {
form.mask_position = stringify(form.mask_position);
}
return this._request('setStickerMaskPosition', { form });
}
|
Use this method to change the [mask position](https://core.telegram.org/bots/api#maskposition) of a mask sticker.
The sticker must belong to a sticker set created by the bot.
@param {String} sticker File identifier of the sticker
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickermaskposition
|
setStickerMaskPosition
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerSetTitle(name, title, form = {}) {
form.name = name;
form.title = title;
return this._request('setStickerSetTitle', { form });
}
|
Use this method to set the title of a created sticker set.
The sticker must belong to a sticker set created by the bot.
@param {String} name Sticker set name
@param {String} title Sticker set title, 1-64 characters
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickersettitle
|
setStickerSetTitle
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setStickerSetThumbnail(userId, name, thumbnail, options = {}, fileOptions = {}) {
const opts = {
qs: options,
};
opts.qs.user_id = userId;
opts.qs.name = name;
opts.qs.mask_position = stringify(options.mask_position);
try {
const sendData = this._formatSendData('thumbnail', thumbnail, fileOptions);
opts.formData = sendData[0];
opts.qs.thumbnail = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setStickerSetThumbnail', opts);
}
|
Use this method to add a thumb to a set created by the bot.
Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only
@param {Number} userId User identifier of sticker set owner
@param {String} name Sticker set name
@param {String|stream.Stream|Buffer} thumbnail A .WEBP or .PNG image with the thumbnail,
must be up to 128 kilobytes in size and have width and height exactly 100px,
a TGS animation with the thumbnail up to 32 kilobytes in size or a WEBM video with the thumbnail up to 32 kilobytes in size.
Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram
to get a file from the Internet, or upload a new one. Animated sticker set thumbnails can't be uploaded via HTTP URL.
@param {Object} [options] Additional Telegram query options
@param {Object} [fileOptions] Optional file related meta-data
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setstickersetthumbnail
|
setStickerSetThumbnail
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setCustomEmojiStickerSetThumbnail(name, form = {}) {
form.name = name;
return this._request('setCustomEmojiStickerSetThumbnail', { form });
}
|
Use this method to set the thumbnail of a custom emoji sticker set.
The sticker must belong to a sticker set created by the bot.
@param {String} name Sticker set name
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail
|
setCustomEmojiStickerSetThumbnail
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
deleteStickerSet(name, form = {}) {
form.name = name;
return this._request('deleteStickerSet', { form });
}
|
Use this method to delete a sticker set that was created by the bot.
The sticker must belong to a sticker set created by the bot.
@param {String} name Sticker set name
@param {Object} [options] Additional Telegram query options
@return {Promise} True on success
@see https://core.telegram.org/bots/api#deletestickerset
|
deleteStickerSet
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
answerInlineQuery(inlineQueryId, results, form = {}) {
form.inline_query_id = inlineQueryId;
form.results = stringify(results);
return this._request('answerInlineQuery', { form });
}
|
Send answers to an inline query.
Note: No more than 50 results per query are allowed.
@param {String} inlineQueryId Unique identifier of the query
@param {InlineQueryResult[]} results An array of results for the inline query
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, True is returned
@see https://core.telegram.org/bots/api#answerinlinequery
|
answerInlineQuery
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
answerWebAppQuery(webAppQueryId, result, form = {}) {
form.web_app_query_id = webAppQueryId;
form.result = stringify(result);
return this._request('answerWebAppQuery', { form });
}
|
Use this method to set the result of an interaction with a [Web App](https://core.telegram.org/bots/webapps)
and send a corresponding message on behalf of the user to the chat from which the query originated.
@param {String} webAppQueryId Unique identifier for the query to be answered
@param {InlineQueryResult} result object that represents one result of an inline query
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, a [SentWebAppMessage](https://core.telegram.org/bots/api#sentwebappmessage) object is returned
@see https://core.telegram.org/bots/api#answerwebappquery
|
answerWebAppQuery
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
sendInvoice(chatId, title, description, payload, providerToken, currency, prices, form = {}) {
form.chat_id = chatId;
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.currency = currency;
form.prices = stringify(prices);
form.provider_data = stringify(form.provider_data);
if (form.suggested_tip_amounts) {
form.suggested_tip_amounts = stringify(form.suggested_tip_amounts);
}
return this._request('sendInvoice', { form });
}
|
Use this method to send an invoice.
@param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
@param {String} title Product name, 1-32 characters
@param {String} description Product description, 1-255 characters
@param {String} payload Bot defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
@param {String} providerToken Payments provider token, obtained via `@BotFather`
@param {String} currency Three-letter ISO 4217 currency code
@param {Array} prices Breakdown of prices
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
@see https://core.telegram.org/bots/api#sendinvoice
|
sendInvoice
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
createInvoiceLink(title, description, payload, providerToken, currency, prices, form = {}) {
form.title = title;
form.description = description;
form.payload = payload;
form.provider_token = providerToken;
form.currency = currency;
form.prices = stringify(prices);
return this._request('createInvoiceLink', { form });
}
|
Use this method to create a link for an invoice.
@param {String} title Product name, 1-32 characters
@param {String} description Product description, 1-255 characters
@param {String} payload Bot defined invoice payload
@param {String} providerToken Payment provider token
@param {String} currency Three-letter ISO 4217 currency code
@param {Array} prices Breakdown of prices
@param {Object} [options] Additional Telegram query options
@returns {Promise} The created invoice link as String on success.
@see https://core.telegram.org/bots/api#createinvoicelink
|
createInvoiceLink
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
answerShippingQuery(shippingQueryId, ok, form = {}) {
form.shipping_query_id = shippingQueryId;
form.ok = ok;
form.shipping_options = stringify(form.shipping_options);
return this._request('answerShippingQuery', { form });
}
|
Use this method to reply to shipping queries.
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
the Bot API will send an [Update](https://core.telegram.org/bots/api#update) with a shipping_query field to the bot
@param {String} shippingQueryId Unique identifier for the query to be answered
@param {Boolean} ok Specify if delivery of the product is possible
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, True is returned
@see https://core.telegram.org/bots/api#answershippingquery
|
answerShippingQuery
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
answerPreCheckoutQuery(preCheckoutQueryId, ok, form = {}) {
form.pre_checkout_query_id = preCheckoutQueryId;
form.ok = ok;
return this._request('answerPreCheckoutQuery', { form });
}
|
Use this method to respond to such pre-checkout queries
Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of
an [Update](https://core.telegram.org/bots/api#update) with the field *pre_checkout_query*.
**Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
@param {String} preCheckoutQueryId Unique identifier for the query to be answered
@param {Boolean} ok Specify if every order details are ok
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, True is returned
@see https://core.telegram.org/bots/api#answerprecheckoutquery
|
answerPreCheckoutQuery
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getStarTransactions(form = {}) {
return this._request('getStarTransactions', { form });
}
|
Use this method for get the bot's Telegram Star transactions in chronological order
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns a [StarTransactions](https://core.telegram.org/bots/api#startransactions) object
@see https://core.telegram.org/bots/api#getstartransactions
|
getStarTransactions
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
refundStarPayment(userId, telegramPaymentChargeId, form = {}) {
form.user_id = userId;
form.telegram_payment_charge_id = telegramPaymentChargeId;
return this._request('refundStarPayment', { form });
}
|
Use this method for refund a successful payment in [Telegram Stars](https://t.me/BotNews/90)
@param {Number} userId Unique identifier of the user whose payment will be refunded
@param {String} telegramPaymentChargeId Telegram payment identifier
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, True is returned
@see https://core.telegram.org/bots/api#refundstarpayment
|
refundStarPayment
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
editUserStarSubscription(userId, telegramPaymentChargeId, isCanceled, form = {}) {
form.user_id = userId;
form.telegram_payment_charge_id = telegramPaymentChargeId;
form.is_canceled = isCanceled;
return this._request('editUserStarSubscription', { form });
}
|
Allows the bot to cancel or re-enable extension of a subscription paid in Telegram Stars.
@param {Number} userId Unique identifier of the user whose subscription will be canceled or re-enabled
@param {String} telegramPaymentChargeId Telegram payment identifier for the subscription
@param {Boolean} isCanceled True, if the subscription should be canceled, False, if it should be re-enabled
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, True is returned
@see https://core.telegram.org/bots/api#cancelrenewsubscription
|
editUserStarSubscription
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
sendGame(chatId, gameShortName, form = {}) {
form.chat_id = chatId;
form.game_short_name = gameShortName;
return this._request('sendGame', { form });
}
|
Use this method to send a game.
@param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
@param {String} gameShortName name of the game to be sent. Set up your games via `@BotFather`.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
@see https://core.telegram.org/bots/api#sendgame
|
sendGame
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setGameScore(userId, score, form = {}) {
form.user_id = userId;
form.score = score;
return this._request('setGameScore', { form });
}
|
Use this method to set the score of the specified user in a game message.
@param {Number} userId Unique identifier of the target user
@param {Number} score New score value, must be non-negative
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, if the message is not an inline message, the [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
@see https://core.telegram.org/bots/api#setgamescore
|
setGameScore
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getGameHighScores(userId, form = {}) {
form.user_id = userId;
return this._request('getGameHighScores', { form });
}
|
Use this method to get data for high score tables.
Will return the score of the specified user and several of their neighbors in a game.
@param {Number} userId Unique identifier of the target user
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns an Array of [GameHighScore](https://core.telegram.org/bots/api#gamehighscore) objects
@see https://core.telegram.org/bots/api#getgamehighscores
|
getGameHighScores
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getAvailableGifts(form = {}) {
return this._request('getAvailableGifts', { form });
}
|
Use this method to returns the list of gifts that can be sent by the bot to users and channel chats.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns a [Gifts](https://core.telegram.org/bots/api#gifts) objects.
@see https://core.telegram.org/bots/api#getavailablegifts
|
getAvailableGifts
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
sendGift(giftId, form = {}) {
form.gift_id = giftId;
return this._request('sendGift', { form });
}
|
Use this method to sends a gift to the given user or channel chat.
@param {String} giftId Unique identifier of the gift
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#getavailablegifts
|
sendGift
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
giftPremiumSubscription(userId, monthCount, starCount, form = {}) {
form.user_id = userId;
form.month_count = monthCount;
form.star_count = starCount;
return this._request('giftPremiumSubscription', { form });
}
|
Use this method to sends a gift to the given user or channel chat.
@param {Number} userId Unique identifier of the target user who will receive a Telegram Premium subscription.
@param {Number} monthCount Number of months the Telegram Premium subscription will be active for the user; must be one of 3, 6, or 12.
@param {String} starCount Number of Telegram Stars to pay for the Telegram Premium subscription; must be 1000 for 3 months, 1500 for 6 months, and 2500 for 12 months.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#getavailablegifts
|
giftPremiumSubscription
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
verifyUser(userId, form = {}) {
form.user_id = userId;
return this._request('verifyUser', { form });
}
|
This method verifies a user [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
@param {Number} userId Unique identifier of the target user.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#verifyuser
|
verifyUser
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
verifyChat(chatId, form = {}) {
form.chat_id = chatId;
return this._request('verifyChat', { form });
}
|
This method verifies a chat [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
@param {Number} chatId Unique identifier of the target chat.
@return {Promise} On success, returns true.
@param {Object} [options] Additional Telegram query options.
@see https://core.telegram.org/bots/api#verifychat
|
verifyChat
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
removeUserVerification(userId, form = {}) {
form.user_id = userId;
return this._request('removeUserVerification', { form });
}
|
This method removes verification from a user who is currently verified [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
@param {Number} userId Unique identifier of the target user
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#removeuserverification
|
removeUserVerification
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
removeChatVerification(chatId, form = {}) {
form.chat_id = chatId;
return this._request('removeChatVerification', { form });
}
|
This method removes verification from a chat who is currently verified [on behalf of the organization](https://telegram.org/verify#third-party-verification) which is represented by the bot.
@param {Number} chatId Unique identifier of the target chat.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#removechatverification
|
removeChatVerification
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
readBusinessMessage(businessConnectionId, chatId, messageId, form = {}) {
form.business_connection_id = businessConnectionId;
form.chat_id = chatId;
form.message_id = messageId;
return this._request('readBusinessMessage', { form });
}
|
This method marks incoming message as read on behalf of a business account.
Requires the **can_read_messages** business bot right
@param {String} businessConnectionId Unique identifier of the business connection on behalf of which to read the message.
@param {Number} chatId Unique identifier of the chat in which the message was received. The chat must have been active in the last 24 hours.
@param {Number} messageId Unique identifier of the message to mark as read.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#readbusinessmessage
|
readBusinessMessage
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
deleteBusinessMessages(businessConnectionId, messageIds, form = {}) {
form.business_connection_id = businessConnectionId;
form.message_ids = stringify(messageIds);
return this._request('deleteBusinessMessages', { form });
}
|
This method delete messages on behalf of a business account.
Requires the **can_delete_outgoing_messages** business bot right to delete messages sent by the bot itself, or the **can_delete_all_messages business** bot right to delete any message.
@param {String} businessConnectionId Unique identifier of the business connection on behalf of which to delete the message.
@param {Number[]} messageIds List of 1-100 identifiers of messages to delete. All messages **must be from the same chat**.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#deletebusinessmessages
|
deleteBusinessMessages
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setBusinessAccountName(businessConnectionId, firstName, form = {}) {
form.business_connection_id = businessConnectionId;
form.first_name = firstName;
return this._request('setBusinessAccountName', { form });
}
|
This method changes the first and last name of a managed business account.
Requires the **can_change_name** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {String} firstName The new value of the first name for the business account; 1-64 characters.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#setbusinessaccountname
|
setBusinessAccountName
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setBusinessAccountUsername(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('setBusinessAccountUsername', { form });
}
|
This method changes the username of a managed business account.
Requires the **can_change_username** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#setbusinessaccountusername
|
setBusinessAccountUsername
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setBusinessAccountBio(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('setBusinessAccountBio', { form });
}
|
This method changes the bio of a managed business account.
Requires the **can_change_bio** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#setbusinessaccountbio
|
setBusinessAccountBio
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setBusinessAccountProfilePhoto(businessConnectionId, photo, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
try {
const sendData = this._formatSendData('photo', photo);
opts.formData = sendData[0];
opts.qs.photo = sendData[1];
} catch (ex) {
return Promise.reject(ex);
}
return this._request('setBusinessAccountProfilePhoto', opts);
}
|
This method changes the profile photo of a managed business account.
Requires the **can_edit_profile_photo** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {String|stream.Stream|Buffer} photo New profile photo.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#setbusinessaccountprofilephoto
|
setBusinessAccountProfilePhoto
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
removeBusinessAccountProfilePhoto(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('removeBusinessAccountProfilePhoto', { form });
}
|
This method removes the current profile photo of a managed business account.
Requires the **can_edit_profile_photo** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#removebusinessaccountprofilephoto
|
removeBusinessAccountProfilePhoto
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
setBusinessAccountGiftSettings(businessConnectionId, showGiftButton, acceptedGiftTypes, form = {}) {
form.business_connection_id = businessConnectionId;
form.show_gift_button = showGiftButton;
form.accepted_gift_types = acceptedGiftTypes;
return this._request('setBusinessAccountGiftSettings', { form });
}
|
This method changes the privacy settings pertaining to incoming gifts in a managed business account.
Requires the **can_change_gift_settings** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Boolean} showGiftButton Pass True, if a button for sending a gift to the user or by the business account must always be shown in the input field.
@param {Object} acceptedGiftTypes Types of gifts accepted by the business account.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns true.
@see https://core.telegram.org/bots/api#setbusinessaccountgiftsettings
|
setBusinessAccountGiftSettings
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getBusinessAccountStarBalance(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('getBusinessAccountStarBalance', { form });
}
|
This method returns the amount of Telegram Stars owned by a managed business account.
Requires the **can_view_gifts_and_stars** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns [StarAmount](https://core.telegram.org/bots/api#staramount).
@see https://core.telegram.org/bots/api#getbusinessaccountstarbalance
|
getBusinessAccountStarBalance
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
transferBusinessAccountStars(businessConnectionId, startCount, form = {}) {
form.business_connection_id = businessConnectionId;
form.star_count = startCount;
return this._request('transferBusinessAccountStars', { form });
}
|
This method transfers Telegram Stars from the business account balance to the bot's balance.
Requires the **can_transfer_stars** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Number} starCount Number of Telegram Stars to transfer; 1-10000.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns True.
@see https://core.telegram.org/bots/api#transferbusinessaccountstars
|
transferBusinessAccountStars
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
getBusinessAccountGifts(businessConnectionId, form = {}) {
form.business_connection_id = businessConnectionId;
return this._request('getBusinessAccountGifts', { form });
}
|
This method returns the gifts received and owned by a managed business account.
Requires the **can_view_gifts_and_stars** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns [OwnedGifts](https://core.telegram.org/bots/api#ownedgifts).
@see https://core.telegram.org/bots/api#getbusinessaccountgifts
|
getBusinessAccountGifts
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
convertGiftToStars(businessConnectionId, ownedGiftId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
return this._request('convertGiftToStars', { form });
}
|
This method converts a given regular gift to Telegram Stars.
Requires the **can_convert_gifts_to_stars** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {String} ownedGiftId Unique identifier of the regular gift that should be converted to Telegram Stars.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns True.
@see https://core.telegram.org/bots/api#convertgifttostars
|
convertGiftToStars
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
upgradeGift(businessConnectionId, ownedGiftId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
return this._request('upgradeGift', { form });
}
|
This method upgrades a given regular gift to a unique gift.
Requires the **can_transfer_and_upgrade_gifts** business bot right.
Additionally requires the **can_transfer_stars** business bot right **if the upgrade is paid**.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {String} ownedGiftId Unique identifier of the regular gift that should be upgraded to a unique one.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns True.
@see https://core.telegram.org/bots/api#upgradegift
|
upgradeGift
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
transferGift(businessConnectionId, ownedGiftId, newOwnerChatId, form = {}) {
form.business_connection_id = businessConnectionId;
form.owned_gift_id = ownedGiftId;
form.new_owner_chat_id = newOwnerChatId;
return this._request('transferGift', { form });
}
|
This method transfers an owned unique gift to another user.
Requires the **can_transfer_and_upgrade_gifts** business bot right.
Additionally requires the **can_transfer_stars** business bot right **if the transfer is paid**.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {String} ownedGiftId Unique identifier of the regular gift that should be transferred.
@param {Number} newOwnerChatId Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns True.
@see https://core.telegram.org/bots/api#transfergift
|
transferGift
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
postStory(businessConnectionId, content, activePeriod, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
opts.qs.active_period = activePeriod;
try {
const inputHistoryContent = content;
opts.formData = {};
if (!content.type) {
return Promise.reject(new Error('content.type is required'));
}
const { formData, fileIds } = this._formatSendMultipleData(content.type, [content]);
opts.formData = formData;
if (fileIds[0]) {
inputHistoryContent[content.type] = fileIds[0];
} else {
inputHistoryContent[content.type] = `attach://${content.type}_0`;
}
opts.qs.content = stringify(inputHistoryContent);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('postStory', opts);
}
|
This method posts a story on behalf of a managed business account.
Requires the **can_manage_stories** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Array} content [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer.
@param {Number} activePeriod Unique identifier of the chat which will own the gift. The chat **must be active in the last 24 hours**.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns [Story](https://core.telegram.org/bots/api#story).
@see https://core.telegram.org/bots/api#poststory
|
postStory
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
editStory(businessConnectionId, storyId, content, options = {}) {
const opts = {
qs: options,
};
opts.qs.business_connection_id = businessConnectionId;
opts.qs.story_id = storyId;
try {
const inputHistoryContent = content;
opts.formData = {};
if (!content.type) {
return Promise.reject(new Error('content.type is required'));
}
const { formData, fileIds } = this._formatSendMultipleData(content.type, [content]);
opts.formData = formData;
if (fileIds[0]) {
inputHistoryContent[content.type] = fileIds[0];
} else {
inputHistoryContent[content.type] = `attach://${content.type}_0`;
}
opts.qs.content = stringify(inputHistoryContent);
} catch (ex) {
return Promise.reject(ex);
}
return this._request('editStory', opts);
}
|
This method edits a story previously posted by the bot on behalf of a managed business account.
Requires the **can_manage_stories** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Number} storyId Unique identifier of the story to edit.
@param {Array} content [InputStoryContent](https://core.telegram.org/bots/api#inputpaidmedia). The photo/video property can be String, Stream or Buffer.
@param {Object} [options] Additional Telegram query options
@return {Promise} On success, returns [Story](https://core.telegram.org/bots/api#story).
@see https://core.telegram.org/bots/api#editstory
|
editStory
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
deleteStory(businessConnectionId, storyId, form = {}) {
form.business_connection_id = businessConnectionId;
form.story_id = storyId;
return this._request('deleteStory', { form });
}
|
This method deletes a story previously posted by the bot on behalf of a managed business account.
Requires the **can_manage_stories** business bot right.
@param {String} businessConnectionId Unique identifier of the business connection.
@param {Number} storyId Unique identifier of the story to delete.
@param {Object} [options] Additional Telegram query options.
@return {Promise} On success, returns True.
@see https://core.telegram.org/bots/api#deletestory
|
deleteStory
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegram.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegram.js
|
MIT
|
constructor(bot) {
this.bot = bot;
this.options = (typeof bot.options.polling === 'boolean') ? {} : bot.options.polling;
this.options.interval = (typeof this.options.interval === 'number') ? this.options.interval : 300;
this.options.params = (typeof this.options.params === 'object') ? this.options.params : {};
this.options.params.offset = (typeof this.options.params.offset === 'number') ? this.options.params.offset : 0;
this.options.params.timeout = (typeof this.options.params.timeout === 'number') ? this.options.params.timeout : 10;
if (typeof this.options.timeout === 'number') {
deprecate('`options.polling.timeout` is deprecated. Use `options.polling.params` instead.');
this.options.params.timeout = this.options.timeout;
}
this._lastUpdate = 0;
this._lastRequest = null;
this._abort = false;
this._pollingTimeout = null;
}
|
Handles polling against the Telegram servers.
@param {TelegramBot} bot
@see https://core.telegram.org/bots/api#getting-updates
|
constructor
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
start(options = {}) {
if (this._lastRequest) {
if (!options.restart) {
return Promise.resolve();
}
return this.stop({
cancel: true,
reason: 'Polling restart',
}).then(() => {
return this._polling();
});
}
return this._polling();
}
|
Start polling
@param {Object} [options]
@param {Object} [options.restart]
@return {Promise}
|
start
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
stop(options = {}) {
if (!this._lastRequest) {
return Promise.resolve();
}
const lastRequest = this._lastRequest;
this._lastRequest = null;
clearTimeout(this._pollingTimeout);
if (options.cancel) {
const reason = options.reason || 'Polling stop';
lastRequest.cancel(reason);
return Promise.resolve();
}
this._abort = true;
return lastRequest.finally(() => {
this._abort = false;
});
}
|
Stop polling
@param {Object} [options] Options
@param {Boolean} [options.cancel] Cancel current request
@param {String} [options.reason] Reason for stopping polling
@return {Promise}
|
stop
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
isPolling() {
return !!this._lastRequest;
}
|
Return `true` if is polling. Otherwise, `false`.
|
isPolling
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
_error(error) {
if (!this.bot.listeners('polling_error').length) {
return console.error('error: [polling_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('polling_error', error);
}
|
Handle error thrown during polling.
@private
@param {Error} error
|
_error
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
_polling() {
this._lastRequest = this
._getUpdates()
.then(updates => {
this._lastUpdate = Date.now();
debug('polling data %j', updates);
updates.forEach(update => {
this.options.params.offset = update.update_id + 1;
debug('updated offset: %s', this.options.params.offset);
try {
this.bot.processUpdate(update);
} catch (err) {
err._processing = true;
throw err;
}
});
return null;
})
.catch(err => {
debug('polling error: %s', err.message);
if (!err._processing) {
return this._error(err);
}
delete err._processing;
/*
* An error occured while processing the items,
* i.e. in `this.bot.processUpdate()` above.
* We need to mark the already-processed items
* to avoid fetching them again once the application
* is restarted, or moves to next polling interval
* (in cases where unhandled rejections do not terminate
* the process).
* See https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067
*/
if (!this.bot.options.badRejection) {
return this._error(err);
}
const opts = {
offset: this.options.params.offset,
limit: 1,
timeout: 0,
};
return this.bot.getUpdates(opts).then(() => {
return this._error(err);
}).catch(requestErr => {
/*
* We have been unable to handle this error.
* We have to log this to stderr to ensure devops
* understands that they may receive already-processed items
* on app restart.
* We simply can not rescue this situation, emit "error"
* event, with the hope that the application exits.
*/
/* eslint-disable no-console */
const bugUrl = 'https://github.com/yagop/node-telegram-bot-api/issues/36#issuecomment-268532067';
console.error('error: Internal handling of The Offset Infinite Loop failed');
console.error(`error: Due to error '${requestErr}'`);
console.error('error: You may receive already-processed updates on app restart');
console.error(`error: Please see ${bugUrl} for more information`);
/* eslint-enable no-console */
return this.bot.emit('error', new errors.FatalError(err));
});
})
.finally(() => {
if (this._abort) {
debug('Polling is aborted!');
} else {
debug('setTimeout for %s miliseconds', this.options.interval);
this._pollingTimeout = setTimeout(() => this._polling(), this.options.interval);
}
});
return this._lastRequest;
}
|
Invokes polling (with recursion!)
@return {Promise} promise of the current request
@private
|
_polling
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
_unsetWebHook() {
debug('unsetting webhook');
return this.bot._request('setWebHook');
}
|
Unset current webhook. Used when we detect that a webhook has been set
and we are trying to poll. Polling and WebHook are mutually exclusive.
@see https://core.telegram.org/bots/api#getting-updates
@private
|
_unsetWebHook
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramPolling.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramPolling.js
|
MIT
|
constructor(bot) {
this.bot = bot;
this.options = (typeof bot.options.webHook === 'boolean') ? {} : bot.options.webHook;
this.options.host = this.options.host || '0.0.0.0';
this.options.port = this.options.port || 8443;
this.options.https = this.options.https || {};
this.options.healthEndpoint = this.options.healthEndpoint || '/healthz';
this._healthRegex = new RegExp(this.options.healthEndpoint);
this._webServer = null;
this._open = false;
this._requestListener = this._requestListener.bind(this);
this._parseBody = this._parseBody.bind(this);
if (this.options.key && this.options.cert) {
debug('HTTPS WebHook enabled (by key/cert)');
this.options.https.key = fs.readFileSync(this.options.key);
this.options.https.cert = fs.readFileSync(this.options.cert);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (this.options.pfx) {
debug('HTTPS WebHook enabled (by pfx)');
this.options.https.pfx = fs.readFileSync(this.options.pfx);
this._webServer = https.createServer(this.options.https, this._requestListener);
} else if (Object.keys(this.options.https).length) {
debug('HTTPS WebHook enabled by (https)');
this._webServer = https.createServer(this.options.https, this._requestListener);
} else {
debug('HTTP WebHook enabled');
this._webServer = http.createServer(this._requestListener);
}
}
|
Sets up a webhook to receive updates
@param {TelegramBot} bot
@see https://core.telegram.org/bots/api#getting-updates
|
constructor
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
open() {
if (this.isOpen()) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this._webServer.listen(this.options.port, this.options.host, () => {
debug('WebHook listening on port %s', this.options.port);
this._open = true;
return resolve();
});
this._webServer.once('error', (err) => {
reject(err);
});
});
}
|
Open WebHook by listening on the port
@return {Promise}
|
open
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
isOpen() {
// NOTE: Since `http.Server.listening` was added in v5.7.0
// and we still need to support Node v4,
// we are going to fallback to 'this._open'.
// The following LOC would suffice for newer versions of Node.js
// return this._webServer.listening;
return this._open;
}
|
Return `true` if server is listening. Otherwise, `false`.
|
isOpen
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
_error(error) {
if (!this.bot.listeners('webhook_error').length) {
return console.error('error: [webhook_error] %j', error); // eslint-disable-line no-console
}
return this.bot.emit('webhook_error', error);
}
|
Handle error thrown during processing of webhook request.
@private
@param {Error} error
|
_error
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
_parseBody(error, body) {
if (error) {
return this._error(new errors.FatalError(error));
}
let data;
try {
data = JSON.parse(body.toString());
} catch (parseError) {
return this._error(new errors.ParseError(parseError.message));
}
return this.bot.processUpdate(data);
}
|
Handle request body by passing it to 'callback'
@private
|
_parseBody
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
_requestListener(req, res) {
debug('WebHook request URL: %s', req.url);
debug('WebHook request headers: %j', req.headers);
if (req.url.indexOf(this.bot.token) !== -1) {
if (req.method !== 'POST') {
debug('WebHook request isn\'t a POST');
res.statusCode = 418; // I'm a teabot!
res.end();
} else {
req
.pipe(bl(this._parseBody))
.on('finish', () => res.end('OK'));
}
} else if (this._healthRegex.test(req.url)) {
debug('WebHook health check passed');
res.statusCode = 200;
res.end('OK');
} else {
debug('WebHook request unauthorized');
res.statusCode = 401;
res.end();
}
}
|
Listener for 'request' event on server
@private
@see https://nodejs.org/docs/latest/api/http.html#http_http_createserver_requestlistener
@see https://nodejs.org/docs/latest/api/https.html#https_https_createserver_options_requestlistener
|
_requestListener
|
javascript
|
yagop/node-telegram-bot-api
|
src/telegramWebHook.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/src/telegramWebHook.js
|
MIT
|
function startMockServer(port, options = {}) {
assert.ok(port);
const server = http.Server((req, res) => {
servers[port].polling = true;
if (options.bad) {
return res.end('can not be parsed with JSON.parse()');
}
return res.end(JSON.stringify({
ok: true,
result: [{
update_id: 0,
message: { text: 'test' },
}],
}));
});
return new Promise((resolve, reject) => {
servers[port] = { server, polling: false };
server.on('error', reject).listen(port, resolve);
});
}
|
Start the static server, serving files in './data'
@param {Number} port
|
startMockServer
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function startStaticServer(port) {
const fileServer = new statics.Server(`${__dirname}/data`);
http.Server((req, res) => {
req.addListener('end', () => {
fileServer.serve(req, res);
}).resume();
}).listen(port);
}
|
Start the static server, serving files in './data'
@param {Number} port
|
startStaticServer
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function isPollingMockServer(port, reverse) {
assert.ok(port);
return new Promise((resolve, reject) => {
// process.nextTick() does not wait until a poll request
// is complete!
setTimeout(() => {
let polling = servers[port] && servers[port].polling;
if (reverse) polling = !polling;
if (polling) return resolve(true);
return reject(new Error('polling-check failed'));
}, 1000);
});
}
|
Start the static server, serving files in './data'
@param {Number} port
|
isPollingMockServer
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function clearPollingCheck(port) {
assert.ok(port);
if (servers[port]) servers[port].polling = false;
}
|
Start the static server, serving files in './data'
@param {Number} port
|
clearPollingCheck
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function hasOpenWebHook(port, reverse) {
assert.ok(port);
const error = new Error('open-webhook-check failed');
let connected = false;
return request.get(`http://127.0.0.1:${port}`)
.then(() => {
connected = true;
}).catch(e => {
if (e.statusCode < 500) connected = true;
}).finally(() => {
if (reverse) {
if (connected) throw error;
return;
}
if (!connected) throw error;
});
}
|
Start the static server, serving files in './data'
@param {Number} port
|
hasOpenWebHook
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function sendWebHookRequest(port, path, options = {}) {
assert.ok(port);
assert.ok(path);
const protocol = options.https ? 'https' : 'http';
const url = `${protocol}://127.0.0.1:${port}${path}`;
return request({
url,
method: options.method || 'POST',
body: options.update || {
update_id: 1,
message: options.message || { text: 'test' }
},
json: (typeof options.json === 'undefined') ? true : options.json,
});
}
|
Start the static server, serving files in './data'
@param {Number} port
|
sendWebHookRequest
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function sendWebHookMessage(port, token, options = {}) {
assert.ok(port);
assert.ok(token);
const path = `/bot${token}`;
return sendWebHookRequest(port, path, options);
}
|
Start the static server, serving files in './data'
@param {Number} port
|
sendWebHookMessage
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function handleRatelimit(bot, methodName, suite) {
const backupMethodName = `__${methodName}`;
if (!bot[backupMethodName]) bot[backupMethodName] = bot[methodName];
const maxRetries = 3;
const addSecs = 5;
const method = bot[backupMethodName];
assert.equal(typeof method, 'function');
bot[methodName] = (...args) => {
let retry = 0;
function exec() {
return method.call(bot, ...args)
.catch(error => {
if (!error.response || error.response.statusCode !== 429) {
throw error;
}
retry++;
if (retry > maxRetries) {
throw error;
}
if (typeof error.response.body === 'string') {
error.response.body = JSON.parse(error.response.body);
}
const retrySecs = error.response.body.parameters.retry_after;
const timeout = (1000 * retrySecs) + (1000 * addSecs);
console.error('tests: Handling rate-limit error. Retrying after %d secs', timeout / 1000); // eslint-disable-line no-console
suite.timeout(timeout * 2);
return new Promise(function timeoutPromise(resolve, reject) {
setTimeout(function execTimeout() {
return exec().then(resolve).catch(reject);
}, timeout);
});
});
}
return exec();
};
return bot;
}
|
Start the static server, serving files in './data'
@param {Number} port
|
handleRatelimit
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function exec() {
return method.call(bot, ...args)
.catch(error => {
if (!error.response || error.response.statusCode !== 429) {
throw error;
}
retry++;
if (retry > maxRetries) {
throw error;
}
if (typeof error.response.body === 'string') {
error.response.body = JSON.parse(error.response.body);
}
const retrySecs = error.response.body.parameters.retry_after;
const timeout = (1000 * retrySecs) + (1000 * addSecs);
console.error('tests: Handling rate-limit error. Retrying after %d secs', timeout / 1000); // eslint-disable-line no-console
suite.timeout(timeout * 2);
return new Promise(function timeoutPromise(resolve, reject) {
setTimeout(function execTimeout() {
return exec().then(resolve).catch(reject);
}, timeout);
});
});
}
|
Start the static server, serving files in './data'
@param {Number} port
|
exec
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function isTelegramFileURI(uri) {
return /https?:\/\/.*\/file\/bot.*\/.*/.test(uri);
}
|
Start the static server, serving files in './data'
@param {Number} port
|
isTelegramFileURI
|
javascript
|
yagop/node-telegram-bot-api
|
test/utils.js
|
https://github.com/yagop/node-telegram-bot-api/blob/master/test/utils.js
|
MIT
|
function optimize(root: ?ASTElement, options: CompilerOptions) {
if (!root) return
isStaticKey = genStaticKeysCached(options.staticKeys || '')
isPlatformReservedTag = options.isReservedTag || no
// first pass: mark all non-static nodes.
markStatic(root)
// second pass: mark static roots.
markStaticRoots(root, false)
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
optimize
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function genStaticKeys(keys: string): Function {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : ''),
)
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
genStaticKeys
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function markStatic(node: ASTNode) {
node.static = isStatic(node)
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (let i = 0, l = node.children.length; i < l; i++) {
const child = node.children[i]
markStatic(child)
if (!child.static) {
node.static = false
}
}
}
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
markStatic
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function markStaticRoots(node: ASTNode, isInFor: boolean) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (
node.static &&
node.children.length &&
!(node.children.length === 1 && node.children[0].type === 3)
) {
node.staticRoot = true
return
} else {
node.staticRoot = false
}
if (node.children) {
for (let i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for)
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor)
}
}
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
markStaticRoots
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function walkThroughConditionsBlocks(
conditionBlocks: ASTIfConditions,
isInFor: boolean,
): void {
for (let i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor)
}
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
walkThroughConditionsBlocks
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function isStatic(node: ASTNode): boolean {
if (node.type === 2) {
// expression
return false
}
if (node.type === 3) {
// text
return true
}
return !!(
node.pre ||
(!node.hasBindings && // no dynamic bindings
!node.if &&
!node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey))
)
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
isStatic
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function isDirectChildOfTemplateFor(node: ASTElement): boolean {
while (node.parent) {
node = node.parent
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
|
Goal of the optimizer: walk the generated template AST tree
and detect sub-trees that are purely static, i.e. parts of
the DOM that never needs to change.
Once we detect these sub-trees, we can:
1. Hoist them into constants, so that we no longer need to
create fresh nodes for them on each re-render;
2. Completely skip them in the patching process.
|
isDirectChildOfTemplateFor
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/optimizer.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/optimizer.js
|
MIT
|
function genComponentModel(
el: ASTElement,
value: string,
modifiers: ?ASTModifiers,
): ?boolean {
const { number, trim } = modifiers || {}
const baseValueExpression = '$$v'
let valueExpression = baseValueExpression
if (trim) {
valueExpression =
`(typeof ${baseValueExpression} === 'string'` +
`? ${baseValueExpression}.trim()` +
`: ${baseValueExpression})`
}
if (number) {
valueExpression = `_n(${valueExpression})`
}
const assignment = genAssignmentCode(value, valueExpression)
el.model = {
value: `(${value})`,
expression: `"${value}"`,
callback: `function (${baseValueExpression}) {${assignment}}`,
}
}
|
Cross-platform code generation for component v-model
|
genComponentModel
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function genAssignmentCode(value: string, assignment: string): string {
const modelRs = parseModel(value)
if (modelRs.idx === null) {
return `${value}=${assignment}`
} else {
return (
`var $$exp = ${modelRs.exp}, $$idx = ${modelRs.idx};` +
`if (!Array.isArray($$exp)){` +
`${value}=${assignment}}` +
`else{$$exp.splice($$idx, 1, ${assignment})}`
)
}
}
|
Cross-platform codegen helper for generating v-model value assignment code.
|
genAssignmentCode
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function parseModel(val: string): Object {
str = val
len = str.length
index = expressionPos = expressionEndPos = 0
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null,
}
}
while (!eof()) {
chr = next()
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr)
} else if (chr === 0x5b) {
parseBracket(chr)
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos),
}
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
parseModel
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function next(): number {
return str.charCodeAt(++index)
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
next
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function eof(): boolean {
return index >= len
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
eof
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function isStringStart(chr: number): boolean {
return chr === 0x22 || chr === 0x27
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
isStringStart
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function parseBracket(chr: number): void {
let inBracket = 1
expressionPos = index
while (!eof()) {
chr = next()
if (isStringStart(chr)) {
parseString(chr)
continue
}
if (chr === 0x5b) inBracket++
if (chr === 0x5d) inBracket--
if (inBracket === 0) {
expressionEndPos = index
break
}
}
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
parseBracket
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function parseString(chr: number): void {
const stringQuote = chr
while (!eof()) {
chr = next()
if (chr === stringQuote) {
break
}
}
}
|
parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
for loop possible cases:
- test
- test[idx]
- test[test1[idx]]
- test["a"][idx]
- xxx.test[a[a].test1[idx]]
- test.xxx.a["asa"][test1[idx]]
|
parseString
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/directives/model.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/directives/model.js
|
MIT
|
function decodeAttr(value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
return value.replace(re, match => decodingMap[match])
}
|
Not type-checking this file because it's mostly vendor code.
|
decodeAttr
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function parseHTML(html, options) {
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
let index = 0
let last, lastTag
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype)
if (doctypeMatch) {
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
handleStartTag(startTagMatch)
continue
}
}
let text, rest, next
if (textEnd >= 0) {
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1)
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
text = html.substring(0, textEnd)
advance(textEnd)
}
if (textEnd < 0) {
text = html
html = ''
}
if (options.chars && text) {
options.chars(text)
}
} else {
var stackedTag = lastTag.toLowerCase()
var reStackedTag =
reCache[stackedTag] ||
(reCache[stackedTag] = new RegExp(
'([\\s\\S]*?)(</' + stackedTag + '[^>]*>)',
'i',
))
var endTagLength = 0
var rest = html.replace(reStackedTag, function(all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (
process.env.NODE_ENV !== 'production' &&
!stack.length &&
options.warn
) {
options.warn(`Mal-formatted tag at end of template: "${html}"`)
}
break
}
}
// Clean up any remaining tags
parseEndTag()
function advance(n) {
index += n
html = html.substring(n)
}
function parseStartTag() {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index,
}
advance(start[0].length)
let end, attr
while (
!(end = html.match(startTagClose)) &&
(attr = html.match(attribute))
) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
function handleStartTag(match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary =
isUnaryTag(tagName) ||
(tagName === 'html' && lastTag === 'head') ||
!!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') {
delete args[3]
}
if (args[4] === '') {
delete args[4]
}
if (args[5] === '') {
delete args[5]
}
}
let value = args[3] || args[4] || args[5] || ''
let name = args[1]
/**
* react-vue change
* <div autorun></div>
* {name: "autorun", value: """"} => {name: "autorun", value: "true"}
*/
if (args[1].indexOf('v-') === -1 && args[2] === undefined) {
value = 'true'
name = ':' + name
}
attrs[i] = {
name: name,
value: decodeAttr(value, options.shouldDecodeNewlines),
}
}
if (!unary) {
stack.push({
tag: tagName,
lowerCasedTag: tagName.toLowerCase(),
attrs: attrs,
})
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
function parseEndTag(tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (
process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(`tag <${stack[i].tag}> has no matching end tag.`)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
|
Not type-checking this file because it's mostly vendor code.
|
parseHTML
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function advance(n) {
index += n
html = html.substring(n)
}
|
Not type-checking this file because it's mostly vendor code.
|
advance
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function parseStartTag() {
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index,
}
advance(start[0].length)
let end, attr
while (
!(end = html.match(startTagClose)) &&
(attr = html.match(attribute))
) {
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
|
Not type-checking this file because it's mostly vendor code.
|
parseStartTag
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function handleStartTag(match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary =
isUnaryTag(tagName) ||
(tagName === 'html' && lastTag === 'head') ||
!!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') {
delete args[3]
}
if (args[4] === '') {
delete args[4]
}
if (args[5] === '') {
delete args[5]
}
}
let value = args[3] || args[4] || args[5] || ''
let name = args[1]
/**
* react-vue change
* <div autorun></div>
* {name: "autorun", value: """"} => {name: "autorun", value: "true"}
*/
if (args[1].indexOf('v-') === -1 && args[2] === undefined) {
value = 'true'
name = ':' + name
}
attrs[i] = {
name: name,
value: decodeAttr(value, options.shouldDecodeNewlines),
}
}
if (!unary) {
stack.push({
tag: tagName,
lowerCasedTag: tagName.toLowerCase(),
attrs: attrs,
})
lastTag = tagName
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
|
Not type-checking this file because it's mostly vendor code.
|
handleStartTag
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function parseEndTag(tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (
process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
options.warn(`tag <${stack[i].tag}> has no matching end tag.`)
}
if (options.end) {
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end)
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
|
react-vue change
<div autorun></div>
{name: "autorun", value: """"} => {name: "autorun", value: "true"}
|
parseEndTag
|
javascript
|
GeekyAnts/vue-native-core
|
src/compiler/parser/html-parser.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/compiler/parser/html-parser.js
|
MIT
|
function bindObjectProps(
data: any,
tag: string,
value: any,
asProp?: boolean,
): VNodeData {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' &&
warn('v-bind without argument expects an Object or Array value', this)
} else {
if (Array.isArray(value)) {
value = toObject(value)
}
let hash
for (const key in value) {
if (key === 'class' || key === 'style') {
hash = data
} else {
const type = data.attrs && data.attrs.type
hash =
asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {})
}
if (!(key in hash)) {
hash[key] = value[key]
}
}
}
}
return data
}
|
Runtime helper for merging v-bind="object" into a VNode's data.
|
bindObjectProps
|
javascript
|
GeekyAnts/vue-native-core
|
src/core/instance/render-helpers/bind-object-props.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/core/instance/render-helpers/bind-object-props.js
|
MIT
|
key
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length)
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i)
}
}
|
Runtime helper for rendering v-for lists.
|
key
|
javascript
|
GeekyAnts/vue-native-core
|
src/core/instance/render-helpers/render-list.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/core/instance/render-helpers/render-list.js
|
MIT
|
isObject(val)) {
keys = Object.keys(val)
ret = new Array(keys.length)
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i]
ret[i] = render(val[key], key, i)
}
}
|
Runtime helper for rendering v-for lists.
|
isObject
|
javascript
|
GeekyAnts/vue-native-core
|
src/core/instance/render-helpers/render-list.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/core/instance/render-helpers/render-list.js
|
MIT
|
function resolveSlots(
children: ?Array<VNode>,
context: ?Component,
): { [key: string]: Array<VNode> }
|
Runtime helper for resolving raw children VNodes into a slot object.
|
resolveSlots
|
javascript
|
GeekyAnts/vue-native-core
|
src/core/instance/render-helpers/resolve-slots.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/core/instance/render-helpers/resolve-slots.js
|
MIT
|
function isWhitespace(node: VNode): boolean {
return node.isComment || node.text === ' '
}
|
Runtime helper for resolving raw children VNodes into a slot object.
|
isWhitespace
|
javascript
|
GeekyAnts/vue-native-core
|
src/core/instance/render-helpers/resolve-slots.js
|
https://github.com/GeekyAnts/vue-native-core/blob/master/src/core/instance/render-helpers/resolve-slots.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.