From be966873befffbb4b9eb32bcee4675c2047b300d Mon Sep 17 00:00:00 2001 From: Pavel Makarenko Date: Tue, 19 Nov 2019 17:55:45 +0300 Subject: [PATCH] basic implementation of multiple bots feature --- .gitignore | 1 + README.md | 4 + lib/nadia.ex | 245 +++------- lib/nadia/api.ex | 119 +---- lib/nadia/bot.ex | 960 +++++++++++++++++++++++++++++++++++++ lib/nadia/bot/api.ex | 138 ++++++ lib/nadia/bot/behaviour.ex | 69 +++ lib/nadia/bot/config.ex | 38 ++ lib/nadia/bot/graph_api.ex | 68 +++ lib/nadia/bot_graph.ex | 176 +++++++ lib/nadia/config.ex | 61 ++- lib/nadia/graph.ex | 50 +- lib/nadia/graph/api.ex | 56 +-- 13 files changed, 1581 insertions(+), 404 deletions(-) create mode 100644 lib/nadia/bot.ex create mode 100644 lib/nadia/bot/api.ex create mode 100644 lib/nadia/bot/behaviour.ex create mode 100644 lib/nadia/bot/config.ex create mode 100644 lib/nadia/bot/graph_api.ex create mode 100644 lib/nadia/bot_graph.ex diff --git a/.gitignore b/.gitignore index a248f1f..cdcf106 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /.idea +/.elixir_ls /_build /config/config.exs /deps diff --git a/README.md b/README.md index 4c92d82..8264c1e 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,10 @@ Now Mix will guarantee the `:nadia` application is started before your applicati ## Usage +There is two ways of using this bot: +- `Nadia` - uses default `:nadia` config section and simplifies configration +- `Nadia.Bot` - uses whatever you pass to it as a bot name + ### get_me ```elixir diff --git a/lib/nadia.ex b/lib/nadia.ex index 2a63fca..8cbd5bd 100644 --- a/lib/nadia.ex +++ b/lib/nadia.ex @@ -7,8 +7,7 @@ defmodule Nadia do """ alias Nadia.Model.{User, Message, Update, UserProfilePhotos, File, Error, WebhookInfo} - - import Nadia.API + alias Nadia.Bot @behaviour Nadia.Behaviour @@ -17,7 +16,7 @@ defmodule Nadia do Returns basic information about the bot in form of a User object. """ @spec get_me :: {:ok, User.t()} | {:error, Error.t()} - def get_me, do: request("getMe") + def get_me, do: Bot.get_me(:nadia) @doc """ Use this method to send text messages. @@ -40,9 +39,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_message(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_message(chat_id, text, options \\ []) do - request("sendMessage", [chat_id: chat_id, text: text] ++ options) - end + def send_message(chat_id, text, options \\ []), + do: Bot.send_message(:nadia, chat_id, text, options) @doc """ Use this method to forward messages of any kind. @@ -57,14 +55,8 @@ defmodule Nadia do * `message_id` - Unique message identifier """ @spec forward_message(integer, integer, integer) :: {:ok, Message.t()} | {:error, Error.t()} - def forward_message(chat_id, from_chat_id, message_id) do - request( - "forwardMessage", - chat_id: chat_id, - from_chat_id: from_chat_id, - message_id: message_id - ) - end + def forward_message(chat_id, from_chat_id, message_id), + do: Bot.forward_message(:nadia, chat_id, from_chat_id, message_id) @doc """ Use this method to send photos. @@ -86,9 +78,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_photo(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_photo(chat_id, photo, options \\ []) do - request("sendPhoto", [chat_id: chat_id, photo: photo] ++ options, :photo) - end + def send_photo(chat_id, photo, options \\ []), + do: Bot.send_photo(:nadia, chat_id, photo, options) @doc """ Use this method to send audio files, if you want Telegram clients to display @@ -121,9 +112,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_audio(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_audio(chat_id, audio, options \\ []) do - request("sendAudio", [chat_id: chat_id, audio: audio] ++ options, :audio) - end + def send_audio(chat_id, audio, options \\ []), + do: Bot.send_audio(:nadia, chat_id, audio, options) @doc """ Use this method to send general files. @@ -146,9 +136,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_document(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_document(chat_id, document, options \\ []) do - request("sendDocument", [chat_id: chat_id, document: document] ++ options, :document) - end + def send_document(chat_id, document, options \\ []), + do: Bot.send_document(:nadia, chat_id, document, options) @doc """ Use this method to send .webp stickers. @@ -169,9 +158,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_sticker(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_sticker(chat_id, sticker, options \\ []) do - request("sendSticker", [chat_id: chat_id, sticker: sticker] ++ options, :sticker) - end + def send_sticker(chat_id, sticker, options \\ []), + do: Bot.send_sticker(:nadia, chat_id, sticker, options) @doc """ Use this method to send video files, Telegram clients support mp4 videos @@ -197,9 +185,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_video(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_video(chat_id, video, options \\ []) do - request("sendVideo", [chat_id: chat_id, video: video] ++ options, :video) - end + def send_video(chat_id, video, options \\ []), + do: Bot.send_video(:nadia, chat_id, video, options) @doc """ Use this method to send audio files, if you want Telegram clients to display @@ -225,9 +212,8 @@ defmodule Nadia do `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` """ @spec send_voice(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_voice(chat_id, voice, options \\ []) do - request("sendVoice", [chat_id: chat_id, voice: voice] ++ options, :voice) - end + def send_voice(chat_id, voice, options \\ []), + do: Bot.send_voice(:nadia, chat_id, voice, options) @doc """ Use this method to send point on the map. @@ -249,12 +235,8 @@ defmodule Nadia do """ @spec send_location(integer, float, float, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_location(chat_id, latitude, longitude, options \\ []) do - request( - "sendLocation", - [chat_id: chat_id, latitude: latitude, longitude: longitude] ++ options - ) - end + def send_location(chat_id, latitude, longitude, options \\ []), + do: Bot.send_location(:nadia, chat_id, latitude, longitude, options) @doc """ Use this method to send information about a venue. @@ -281,13 +263,8 @@ defmodule Nadia do """ @spec send_venue(integer, float, float, binary, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_venue(chat_id, latitude, longitude, title, address, options \\ []) do - request( - "sendVenue", - [chat_id: chat_id, latitude: latitude, longitude: longitude, title: title, address: address] ++ - options - ) - end + def send_venue(chat_id, latitude, longitude, title, address, options \\ []), + do: Bot.send_venue(:nadia, chat_id, latitude, longitude, title, address, options) @doc """ Use this method to send phone contacts. @@ -312,12 +289,8 @@ defmodule Nadia do """ @spec send_contact(integer, binary, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_contact(chat_id, phone_number, first_name, options \\ []) do - request( - "sendContact", - [chat_id: chat_id, phone_number: phone_number, first_name: first_name] ++ options - ) - end + def send_contact(chat_id, phone_number, first_name, options \\ []), + do: Bot.send_contact(:nadia, chat_id, phone_number, first_name, options) @doc """ Use this method when you need to tell the user that something is happening on @@ -337,40 +310,37 @@ defmodule Nadia do * `find_location` for location data """ @spec send_chat_action(integer, binary) :: :ok | {:error, Error.t()} - def send_chat_action(chat_id, action) do - request("sendChatAction", chat_id: chat_id, action: action) - end + def send_chat_action(chat_id, action), do: Bot.send_chat_action(:nadia, chat_id, action) @doc """ - Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). - On success, the sent Message is returned. Bots can currently send animation files of up + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. Args: - * `chat_id` - Unique identifier for the target chat or username of the target channel + * `chat_id` - Unique identifier for the target chat or username of the target channel (in the format @channelusername) - * `animation` - Animation to send. Pass a file_id as String to send an animation that - exists on the Telegram servers (recommended), pass an HTTP URL as a String for + * `animation` - Animation to send. Pass a file_id as String to send an animation that + exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. Options: * `:duration` - Duration of sent animation in seconds * `:width` - Animation width * `:height` - Animation height - * `:thumb` - Thumbnail of the file sent; can be ignored if thumbnail generation for the file + * `:thumb` - Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. thumbnail should be in JPEG format and less than 200 kB in size. * `:caption` - Animation caption (may also be used when resending animation by file_id), 0-1024 characters - * `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width + * `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in the media caption. * `:disable_notification` - Sends the message silently. Users will receive a notification with no sound. * `:reply_to_message_id` - If the message is a reply, ID of the original message - * `:reply_markup` - Additional interface options. A JSON-serialized object for an inline keyboard, + * `:reply_markup` - Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. """ @spec send_animation(integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def send_animation(chat_id, animation, options \\ []) do - request("sendAnimation", [chat_id: chat_id, animation: animation] ++ options) - end + def send_animation(chat_id, animation, options \\ []), + do: Bot.send_animation(:nadia, chat_id, animation, options) @doc """ Use this method to get a list of profile pictures for a user. @@ -388,9 +358,8 @@ defmodule Nadia do """ @spec get_user_profile_photos(integer, [{atom, any}]) :: {:ok, UserProfilePhotos.t()} | {:error, Error.t()} - def get_user_profile_photos(user_id, options \\ []) do - request("getUserProfilePhotos", [user_id: user_id] ++ options) - end + def get_user_profile_photos(user_id, options \\ []), + do: Bot.get_user_profile_photos(:nadia, user_id, options) @doc """ Use this method to receive incoming updates using long polling. @@ -411,7 +380,7 @@ defmodule Nadia do polling """ @spec get_updates([{atom, any}]) :: {:ok, [Update.t()]} | {:error, Error.t()} - def get_updates(options \\ []), do: request("getUpdates", options) + def get_updates(options \\ []), do: Bot.get_updates(:nadia, options) @doc """ Use this method to specify a url and receive incoming updates via an outgoing @@ -426,7 +395,7 @@ defmodule Nadia do * `:url` - HTTPS url to send updates to. """ @spec set_webhook([{atom, any}]) :: :ok | {:error, Error.t()} - def set_webhook(options \\ []), do: request("setWebhook", options) + def set_webhook(options \\ []), do: Bot.set_webhook(:nadia, options) @doc """ Use this method to remove webhook integration if you decide to switch back to `Nadia.get_updates/1`. @@ -435,7 +404,7 @@ defmodule Nadia do Requires no parameters. """ @spec delete_webhook() :: :ok | {:error, Error.t()} - def delete_webhook(), do: request("deleteWebhook") + def delete_webhook(), do: Bot.delete_webhook(:nadia) @doc """ Use this method to get current webhook status. Requires no parameters. @@ -443,7 +412,7 @@ defmodule Nadia do If the bot is using getUpdates, will return an object with the url field empty. """ @spec get_webhook_info() :: {:ok, WebhookInfo.t()} | {:error, Error.t()} - def get_webhook_info(), do: request("getWebhookInfo") + def get_webhook_info(), do: Bot.get_webhook_info(:nadia) @doc """ Use this method to get basic info about a file and prepare it for downloading. @@ -458,7 +427,7 @@ defmodule Nadia do * `file_id` - File identifier to get info about """ @spec get_file(binary) :: {:ok, File.t()} | {:error, Error.t()} - def get_file(file_id), do: request("getFile", file_id: file_id) + def get_file(file_id), do: Bot.get_file(:nadia, file_id) @doc ~S""" Use this method to get link for file for subsequent use. @@ -471,9 +440,7 @@ defmodule Nadia do """ @spec get_file_link(File.t()) :: {:ok, binary} | {:error, Error.t()} - def get_file_link(file) do - {:ok, build_file_url(file.file_path)} - end + def get_file_link(file), do: Bot.get_file_link(:nadia, file) @doc """ Use this method to kick a user from a group or a supergroup. In the case of supergroups, @@ -491,9 +458,7 @@ defmodule Nadia do * `user_id` - Unique identifier of the target user """ @spec kick_chat_member(integer | binary, integer) :: :ok | {:error, Error.t()} - def kick_chat_member(chat_id, user_id) do - request("kickChatMember", chat_id: chat_id, user_id: user_id) - end + def kick_chat_member(chat_id, user_id), do: Bot.kick_chat_member(:nadia, chat_id, user_id) @doc """ Use this method for your bot to leave a group, supergroup or channel. @@ -504,9 +469,7 @@ defmodule Nadia do channel (in the format @supergroupusername) """ @spec leave_chat(integer | binary) :: :ok | {:error, Error.t()} - def leave_chat(chat_id) do - request("leaveChat", chat_id: chat_id) - end + def leave_chat(chat_id), do: Bot.leave_chat(:nadia, chat_id) @doc """ Use this method to unban a previously kicked user in a supergroup. The user will not @@ -519,9 +482,7 @@ defmodule Nadia do * `user_id` - Unique identifier of the target user """ @spec unban_chat_member(integer | binary, integer) :: :ok | {:error, Error.t()} - def unban_chat_member(chat_id, user_id) do - request("unbanChatMember", chat_id: chat_id, user_id: user_id) - end + def unban_chat_member(chat_id, user_id), do: Bot.unban_chat_member(:nadia, chat_id, user_id) @doc """ Use this method to get up to date information about the chat (current name of @@ -533,9 +494,7 @@ defmodule Nadia do channel (in the format @supergroupusername) """ @spec get_chat(integer | binary) :: {:ok, Chat.t()} | {:error, Error.t()} - def get_chat(chat_id) do - request("getChat", chat_id: chat_id) - end + def get_chat(chat_id), do: Bot.get_chat(:nadia, chat_id) @doc """ Use this method to get a list of administrators in a chat. On success, returns an Array of @@ -548,9 +507,7 @@ defmodule Nadia do channel (in the format @channelusername) """ @spec get_chat_administrators(integer | binary) :: {:ok, [ChatMember.t()]} | {:error, Error.t()} - def get_chat_administrators(chat_id) do - request("getChatAdministrators", chat_id: chat_id) - end + def get_chat_administrators(chat_id), do: Bot.get_chat_administrators(:nadia, chat_id) @doc """ Use this method to get the number of members in a chat. Returns Int on success. @@ -560,9 +517,7 @@ defmodule Nadia do channel (in the format @channelusername) """ @spec get_chat_members_count(integer | binary) :: {:ok, integer} | {:error, Error.t()} - def get_chat_members_count(chat_id) do - request("getChatMembersCount", chat_id: chat_id) - end + def get_chat_members_count(chat_id), do: Bot.get_chat_members_count(:nadia, chat_id) @doc """ Use this method to get information about a member of a chat. @@ -574,9 +529,7 @@ defmodule Nadia do * `user_id` - Unique identifier of the target user """ @spec get_chat_member(integer | binary, integer) :: {:ok, ChatMember.t()} | {:error, Error.t()} - def get_chat_member(chat_id, user_id) do - request("getChatMember", chat_id: chat_id, user_id: user_id) - end + def get_chat_member(chat_id, user_id), do: Bot.get_chat_member(:nadia, chat_id, user_id) @doc """ Use this method to send answers to callback queries sent from inline keyboards. @@ -594,9 +547,8 @@ defmodule Nadia do notification at the top of the chat screen. Defaults to false. """ @spec answer_callback_query(binary, [{atom, any}]) :: :ok | {:error, Error.t()} - def answer_callback_query(callback_query_id, options \\ []) do - request("answerCallbackQuery", [callback_query_id: callback_query_id] ++ options) - end + def answer_callback_query(callback_query_id, options \\ []), + do: Bot.answer_callback_query(callback_query_id, options) @doc """ Use this method to edit text messages sent by the bot or via the bot (for inline bots). @@ -621,13 +573,8 @@ defmodule Nadia do """ @spec edit_message_text(integer | binary, integer, binary, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def edit_message_text(chat_id, message_id, inline_message_id, text, options \\ []) do - request( - "editMessageText", - [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id, text: text] ++ - options - ) - end + def edit_message_text(chat_id, message_id, inline_message_id, text, options \\ []), + do: Bot.edit_message_text(chat_id, message_id, inline_message_id, text, options) @doc """ Use this method to delete message from a chat. @@ -641,13 +588,7 @@ defmodule Nadia do the sent message """ @spec delete_message(integer | binary, integer) :: :ok | {:error, Error.t()} - def delete_message(chat_id, message_id) do - request( - "deleteMessage", - chat_id: chat_id, - message_id: message_id - ) - end + def delete_message(chat_id, message_id), do: Bot.delete_message(:nadia, chat_id, message_id) @doc """ Use this method to edit captions of messages sent by the bot or via @@ -669,12 +610,8 @@ defmodule Nadia do """ @spec edit_message_caption(integer | binary, integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def edit_message_caption(chat_id, message_id, inline_message_id, options \\ []) do - request( - "editMessageCaption", - [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options - ) - end + def edit_message_caption(chat_id, message_id, inline_message_id, options \\ []), + do: Bot.edit_message_caption(:nadia, chat_id, message_id, inline_message_id, options) @doc """ Use this method to edit only the reply markup of messages sent by the bot or via @@ -695,12 +632,8 @@ defmodule Nadia do """ @spec edit_message_reply_markup(integer | binary, integer, binary, [{atom, any}]) :: {:ok, Message.t()} | {:error, Error.t()} - def edit_message_reply_markup(chat_id, message_id, inline_message_id, options \\ []) do - request( - "editMessageReplyMarkup", - [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options - ) - end + def edit_message_reply_markup(chat_id, message_id, inline_message_id, options \\ []), + do: Bot.edit_message_reply_markup(:nadia, chat_id, message_id, inline_message_id, options) @doc """ Use this method to send answers to an inline query. On success, True is returned. @@ -728,18 +661,8 @@ defmodule Nadia do """ @spec answer_inline_query(binary, [Nadia.Model.InlineQueryResult.t()], [{atom, any}]) :: :ok | {:error, Error.t()} - def answer_inline_query(inline_query_id, results, options \\ []) do - encoded_results = - results - |> Enum.map(fn result -> - for {k, v} <- Map.from_struct(result), v != nil, into: %{}, do: {k, v} - end) - |> Jason.encode!() - - args = [inline_query_id: inline_query_id, results: encoded_results] - - request("answerInlineQuery", args ++ options) - end + def answer_inline_query(inline_query_id, results, options \\ []), + do: Bot.answer_inline_query(:nadia, inline_query_id, results, options) @doc """ Use this method to get a sticker set. On success, a StickerSet object is returned. @@ -748,9 +671,7 @@ defmodule Nadia do * `name` - Name of the sticker set """ @spec get_sticker_set(binary) :: {:ok, Nadia.Model.StickerSet.t()} | {:error, Error.t()} - def get_sticker_set(name) do - request("getStickerSet", name: name) - end + def get_sticker_set(name), do: Bot.get_sticker_set(:nadia, name) @doc """ Use this method to upload a .png file with a sticker for later use in @@ -766,9 +687,8 @@ defmodule Nadia do from the internet. """ @spec upload_sticker_file(integer, binary) :: {:ok, File.t()} | {:error, Error.t()} - def upload_sticker_file(user_id, png_sticker) do - request("uploadStickerFile", [user_id: user_id, png_sticker: png_sticker], :png_sticker) - end + def upload_sticker_file(user_id, png_sticker), + do: Bot.upload_sticker_file(:nadia, user_id, png_sticker) @doc """ Use this method to create new sticker set owned by a user. The bot will be able to @@ -795,14 +715,8 @@ defmodule Nadia do """ @spec create_new_sticker_set(integer, binary, binary, binary, binary, [{atom, any}]) :: :ok | {:error, Error.t()} - def create_new_sticker_set(user_id, name, title, png_sticker, emojis, options \\ []) do - request( - "createNewStickerSet", - [user_id: user_id, name: name, title: title, png_sticker: png_sticker, emojis: emojis] ++ - options, - :png_sticker - ) - end + def create_new_sticker_set(user_id, name, title, png_sticker, emojis, options \\ []), + do: Bot.create_new_sticker_set(:nadia, user_id, name, title, png_sticker, emojis, options) @doc """ Use this method to add a new sticker to a set created by the bot. Returns True on success. @@ -823,13 +737,8 @@ defmodule Nadia do """ @spec add_sticker_to_set(integer, binary, binary, binary, [{atom, any}]) :: :ok | {:error, Error.t()} - def add_sticker_to_set(user_id, name, png_sticker, emojis, options \\ []) do - request( - "addStickerToSet", - [user_id: user_id, name: name, png_sticker: png_sticker, emojis: emojis] ++ options, - :png_sticker - ) - end + def add_sticker_to_set(user_id, name, png_sticker, emojis, options \\ []), + do: Bot.add_sticker_to_set(:nadia, user_id, name, png_sticker, emojis, options) @doc """ Use this method to move a sticker in a set created by the bot to a specific position. @@ -840,9 +749,8 @@ defmodule Nadia do * `position` - New sticker position in the set, zero-based """ @spec set_sticker_position_in_set(binary, integer) :: :ok | {:error, Error.t()} - def set_sticker_position_in_set(sticker, position) do - request("setStickerPositionInSet", sticker: sticker, position: position) - end + def set_sticker_position_in_set(sticker, position), + do: Bot.set_sticker_position_in_set(:nadia, sticker, position) @doc """ Use this method to delete a sticker from a set created by the bot. Returns True on success. @@ -851,9 +759,7 @@ defmodule Nadia do * `sticker` - File identifier of the sticker """ @spec delete_sticker_from_set(binary) :: :ok | {:error, Error.t()} - def delete_sticker_from_set(sticker) do - request("deleteStickerFromSet", sticker: sticker) - end + def delete_sticker_from_set(sticker), do: Bot.delete_sticker_from_set(:nadia, sticker) @doc """ Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an @@ -871,9 +777,8 @@ defmodule Nadia do """ @spec pin_chat_message(integer | binary, integer | binary, [{atom, any}]) :: :ok | {:error, Error.t()} - def pin_chat_message(chat_id, message_id, options \\ []) do - request("pinChatMessage", [chat_id: chat_id, message_id: message_id] ++ options) - end + def pin_chat_message(chat_id, message_id, options \\ []), + do: Bot.pin_chat_message(:nadia, chat_id, message_id, options) @doc """ Use this method to unpin a message in a group, a supergroup, or a channel. The bot must be an @@ -885,7 +790,5 @@ defmodule Nadia do (in the format @channelusername) """ @spec unpin_chat_message(integer | binary) :: :ok | {:error, Error.t()} - def unpin_chat_message(chat_id) do - request("unpinChatMessage", chat_id: chat_id) - end + def unpin_chat_message(chat_id), do: Bot.unpin_chat_message(:nadia, chat_id) end diff --git a/lib/nadia/api.ex b/lib/nadia/api.ex index df6db00..28c8426 100644 --- a/lib/nadia/api.ex +++ b/lib/nadia/api.ex @@ -3,106 +3,7 @@ defmodule Nadia.API do Provides basic functionalities for Telegram Bot API. """ - alias Nadia.Model.Error - alias Nadia.Config - - defp build_url(method), do: Config.base_url() <> Config.token() <> "/" <> method - - defp process_response(response, method) do - case decode_response(response) do - {:ok, true} -> :ok - {:ok, %{ok: false, description: description}} -> {:error, %Error{reason: description}} - {:ok, result} -> {:ok, Nadia.Parser.parse_result(result, method)} - {:error, %HTTPoison.Error{reason: reason}} -> {:error, %Error{reason: reason}} - {:error, error} -> {:error, %Error{reason: error}} - end - end - - defp decode_response(response) do - with {:ok, %HTTPoison.Response{body: body}} <- response, - {:ok, %{result: result}} <- Jason.decode(body, keys: :atoms), - do: {:ok, result} - end - - defp build_multipart_request(params, file_field) do - {file_path, params} = Keyword.pop(params, file_field) - params = for {k, v} <- params, do: {to_string(k), v} - - {:multipart, - params ++ - [ - {:file, file_path, - {"form-data", [{"name", to_string(file_field)}, {"filename", file_path}]}, []} - ]} - end - - defp calculate_timeout(options) when is_list(options) do - (Keyword.get(options, :timeout, 0) + Config.recv_timeout()) * 1000 - end - - defp calculate_timeout(options) when is_map(options) do - (Map.get(options, :timeout, 0) + Config.recv_timeout()) * 1000 - end - - defp build_request(params, file_field) when is_list(params) do - params - |> Keyword.update(:reply_markup, nil, &Jason.encode!(&1)) - |> map_params(file_field) - end - - defp build_request(params, file_field) when is_map(params) do - params - |> Map.update(:reply_markup, nil, &Jason.encode!(&1)) - |> map_params(file_field) - end - - defp map_params(params, file_field) do - params = - params - |> Enum.filter(fn {_, v} -> v end) - |> Enum.map(fn {k, v} -> {k, to_string(v)} end) - - if !is_nil(file_field) and File.exists?(params[file_field]) do - build_multipart_request(params, file_field) - else - {:form, params} - end - end - - defp build_options(options) do - timeout = calculate_timeout(options) - opts = [recv_timeout: timeout] - - opts = - case Config.proxy() do - proxy when byte_size(proxy) > 0 -> Keyword.put(opts, :proxy, proxy) - proxy when is_tuple(proxy) and tuple_size(proxy) == 3 -> Keyword.put(opts, :proxy, proxy) - _ -> opts - end - - opts = - case Config.proxy_auth() do - proxy_auth when is_tuple(proxy_auth) and tuple_size(proxy_auth) == 2 -> - Keyword.put(opts, :proxy_auth, proxy_auth) - - _ -> - opts - end - - opts = - case Config.socks5_user() do - socks5_user when byte_size(socks5_user) > 0 -> - Keyword.put(opts, :socks5_user, socks5_user) - - _ -> - opts - end - - case Config.socks5_pass() do - socks5_pass when byte_size(socks5_pass) > 0 -> Keyword.put(opts, :socks5_pass, socks5_pass) - _ -> opts - end - end + alias Nadia.Bot.API @doc """ Generic method to call Telegram Bot API. @@ -113,17 +14,11 @@ defmodule Nadia.API do * `file_field` - specify the key of file_field in `options` when sending files """ @spec request(binary, [{atom, any}], atom) :: :ok | {:error, Error.t()} | {:ok, any} - def request(method, options \\ [], file_field \\ nil) do - method - |> build_url - |> HTTPoison.post(build_request(options, file_field), [], build_options(options)) - |> process_response(method) - end + def request(method, options \\ [], file_field \\ nil), + do: API.request(:nadia, method, options, file_field) - def request?(method, options \\ [], file_field \\ nil) do - {_, response} = request(method, options, file_field) - response - end + def request?(method, options \\ [], file_field \\ nil), + do: API.request?(:nadia, method, options, file_field) @doc ~S""" Use this function to build file url. @@ -132,7 +27,5 @@ defmodule Nadia.API do "https://api.telegram.org/file/bot#{Nadia.Config.token()}/document/file_10" """ @spec build_file_url(binary) :: binary - def build_file_url(file_path) do - Config.file_base_url() <> Config.token() <> "/" <> file_path - end + def build_file_url(file_path), do: API.build_file_url(:nadia, file_path) end diff --git a/lib/nadia/bot.ex b/lib/nadia/bot.ex new file mode 100644 index 0000000..f1bc235 --- /dev/null +++ b/lib/nadia/bot.ex @@ -0,0 +1,960 @@ +defmodule Nadia.Bot do + @moduledoc """ + Provides access to Telegram Bot API. + + ## Reference + https://core.telegram.org/bots/api#available-methods + """ + + alias Nadia.Model.{Message, Update, UserProfilePhotos, File, Error, WebhookInfo} + + import Nadia.Bot.API + + @behaviour Nadia.Bot.Behaviour + + @doc """ + A simple method for testing your bot's auth token. Requires no parameters. + Returns basic information about the bot in form of a User object. + + Args: + * `bot` - Bot name + """ + @spec get_me(atom) :: {:ok, Message.t()} | {:error, Error.t()} + def get_me(bot), do: request(bot, "getMe") + + @doc """ + Use this method to send text messages. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `text` - Text of the message to be sent + * `options` - orddict of options + + Options: + * `:parse_mode` - Use `Markdown`, if you want Telegram apps to show bold, italic + and inline URLs in your bot's message + * `:disable_web_page_preview` - Disables link previews for links in this message + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_message(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_message(bot, chat_id, text, options \\ []) do + request(bot, "sendMessage", [chat_id: chat_id, text: text] ++ options) + end + + @doc """ + Use this method to forward messages of any kind. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `from_chat_id` - Unique identifier for the chat where the original message was sent + or username of the target channel (in the format @channelusername) + * `:disable_notification` - Sends the message silently or without notification + * `message_id` - Unique message identifier + """ + @spec forward_message(atom, integer, integer, integer) :: + {:ok, Message.t()} | {:error, Error.t()} + def forward_message(bot, chat_id, from_chat_id, message_id) do + request( + bot, + "forwardMessage", + chat_id: chat_id, + from_chat_id: from_chat_id, + message_id: message_id + ) + end + + @doc """ + Use this method to send photos. + On success, the sent Message is returned. + + Args: + * `bot`- Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `photo` - Photo to send. Either a `file_id` to resend a photo that is already on + the Telegram servers, or a `file_path` to upload a new photo + * `options` - orddict of options + + Options: + * `:caption` - Photo caption (may also be used when resending photos by `file_id`) + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_photo(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_photo(bot, chat_id, photo, options \\ []) do + request(bot, "sendPhoto", [chat_id: chat_id, photo: photo] ++ options, :photo) + end + + @doc """ + Use this method to send audio files, if you want Telegram clients to display + them in the music player. Your audio must be in the .mp3 format. + On success, the sent Message is returned. + Bots can currently send audio files of up to 50 MB in size, this limit may + be changed in the future. + + For backward compatibility, when the fields title and performer are both + empty and the mime-type of the file to be sent is not audio/mpeg, the file + will be sent as a playable voice message. For this to work, the audio must be + in an .ogg file encoded with OPUS. This behavior will be phased out in the + future. For sending voice messages, use the sendVoice method instead. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `audio` - Audio to send. Either a `file_id` to resend an audio that is already on + the Telegram servers, or a `file_path` to upload a new audio + * `options` - orddict of options + + Options: + * `:duration` - Duration of the audio in seconds + * `:performer` - Performer + * `:title` - Track name + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_audio(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_audio(bot, chat_id, audio, options \\ []) do + request(bot, "sendAudio", [chat_id: chat_id, audio: audio] ++ options, :audio) + end + + @doc """ + Use this method to send general files. + On success, the sent Message is returned. + Bots can currently send files of any type of up to 50 MB in size, this limit + may be changed in the future. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `document` - File to send. Either a `file_id` to resend a file that is already on + the Telegram servers, or a `file_path` to upload a new file + * `options` - orddict of options + + Options: + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_document(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_document(bot, chat_id, document, options \\ []) do + request(bot, "sendDocument", [chat_id: chat_id, document: document] ++ options, :document) + end + + @doc """ + Use this method to send .webp stickers. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `sticker` - File to send. Either a `file_id` to resend a sticker that is already on + the Telegram servers, or a `file_path` to upload a new sticker + * `options` - orddict of options + + Options: + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_sticker(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_sticker(bot, chat_id, sticker, options \\ []) do + request(bot, "sendSticker", [chat_id: chat_id, sticker: sticker] ++ options, :sticker) + end + + @doc """ + Use this method to send video files, Telegram clients support mp4 videos + (other formats may be sent as Document). + On success, the sent Message is returned. + Bots can currently send video files of up to 50 MB in size, this limit may be + changed in the future. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `video` - Video to send. Either a `file_id` to resend a video that is already on + the Telegram servers, or a `file_path` to upload a new video + * `options` - orddict of options + + Options: + * `:duration` - Duration of the video in seconds + * `:caption` - Video caption (may also be used when resending videos by `file_id`) + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_video(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_video(bot, chat_id, video, options \\ []) do + request(bot, "sendVideo", [chat_id: chat_id, video: video] ++ options, :video) + end + + @doc """ + Use this method to send audio files, if you want Telegram clients to display + the file as a playable voice message. For this to work, your audio must be in + an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). + On success, the sent Message is returned. + Bots can currently send voice messages of up to 50 MB in size, this limit may be + changed in the future. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `voice` - Audio to send. Either a `file_id` to resend an audio that is already on + the Telegram servers, or a `file_path` to upload a new audio + * `options` - orddict of options + + Options: + * `:duration` - Duration of the audio in seconds + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_voice(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_voice(bot, chat_id, voice, options \\ []) do + request(bot, "sendVoice", [chat_id: chat_id, voice: voice] ++ options, :voice) + end + + @doc """ + Use this method to send point on the map. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `latitude` - Latitude of location + * `longitude` - Longitude of location + * `options` - orddict of options + + Options: + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. Instructions to hide keyboard or to + force a reply from the user - `Nadia.Model.ReplyKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardRemove` or `Nadia.Model.ForceReply` + """ + @spec send_location(atom, integer, float, float, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_location(bot, chat_id, latitude, longitude, options \\ []) do + request( + bot, + "sendLocation", + [chat_id: chat_id, latitude: latitude, longitude: longitude] ++ options + ) + end + + @doc """ + Use this method to send information about a venue. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `latitude` - Latitude of location + * `longitude` - Longitude of location + * `title` - Name of the venue + * `address` - Address of the venue + * `options` - orddict of options + + Options: + * `:foursquare_id` - Foursquare identifier of the venue + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. A JSON-serialized object for + an inline keyboard, custom reply keyboard, instructions to hide reply keyboard + or to force a reply from the user. - `Nadia.Model.InlineKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardMarkup` or `Nadia.Model.ReplyKeyboardRemove` or + `Nadia.Model.ForceReply` + """ + @spec send_venue(atom, integer, float, float, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_venue(bot, chat_id, latitude, longitude, title, address, options \\ []) do + request( + bot, + "sendVenue", + [chat_id: chat_id, latitude: latitude, longitude: longitude, title: title, address: address] ++ + options + ) + end + + @doc """ + Use this method to send phone contacts. + On success, the sent Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `phone_number` - Contact's phone number + * `first_name` - Contact's first name + * `options` - orddict of options + + Options: + * `:last_name` - Contact's last name + * `:disable_notification` - Sends the message silently or without notification + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. A JSON-serialized object for + an inline keyboard, custom reply keyboard, instructions to hide reply keyboard + or to force a reply from the user. - `Nadia.Model.InlineKeyboardMarkup` or + `Nadia.Model.ReplyKeyboardMarkup` or `Nadia.Model.ReplyKeyboardRemove` or + `Nadia.Model.ForceReply` + """ + @spec send_contact(atom, integer, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_contact(bot, chat_id, phone_number, first_name, options \\ []) do + request( + bot, + "sendContact", + [chat_id: chat_id, phone_number: phone_number, first_name: first_name] ++ options + ) + end + + @doc """ + Use this method when you need to tell the user that something is happening on + the bot's side. The status is set for 5 seconds or less (when a message + arrives from your bot, Telegram clients clear its typing status). + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `action` - Type of action to broadcast. Choose one, depending on what the user is + about to receive: + * `typing` for text messages + * `upload_photo` for photos + * `record_video` or `upload_video` for videos + * `record_audio` or `upload_audio` for audio files + * `upload_document` for general files + * `find_location` for location data + """ + @spec send_chat_action(atom, integer, binary) :: :ok | {:error, Error.t()} + def send_chat_action(bot, chat_id, action) do + request(bot, "sendChatAction", chat_id: chat_id, action: action) + end + + @doc """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). + On success, the sent Message is returned. Bots can currently send animation files of up + to 50 MB in size, this limit may be changed in the future. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `animation` - Animation to send. Pass a file_id as String to send an animation that + exists on the Telegram servers (recommended), pass an HTTP URL as a String for + Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. + + Options: + * `:duration` - Duration of sent animation in seconds + * `:width` - Animation width + * `:height` - Animation height + * `:thumb` - Thumbnail of the file sent; can be ignored if thumbnail generation for the file + is supported server-side. thumbnail should be in JPEG format and less than 200 kB in size. + * `:caption` - Animation caption (may also be used when resending animation by file_id), 0-1024 characters + * `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width + text or inline URLs in the media caption. + * `:disable_notification` - Sends the message silently. Users will receive a notification with no sound. + * `:reply_to_message_id` - If the message is a reply, ID of the original message + * `:reply_markup` - Additional interface options. A JSON-serialized object for an inline keyboard, + custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. + """ + @spec send_animation(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def send_animation(bot, chat_id, animation, options \\ []) do + request(bot, "sendAnimation", [chat_id: chat_id, animation: animation] ++ options) + end + + @doc """ + Use this method to get a list of profile pictures for a user. + Returns a UserProfilePhotos object. + + Args: + * `bot` - Bot name + * `user_id` - Unique identifier of the target user + * `options` - orddict of options + + Options: + * `:offset` - Sequential number of the first photo to be returned. By default, all + photos are returned + * `:limit` - Limits the number of photos to be retrieved. Values between 1—100 are + accepted. Defaults to 100 + """ + @spec get_user_profile_photos(atom, integer, [{atom, any}]) :: + {:ok, UserProfilePhotos.t()} | {:error, Error.t()} + def get_user_profile_photos(bot, user_id, options \\ []) do + request(bot, "getUserProfilePhotos", [user_id: user_id] ++ options) + end + + @doc """ + Use this method to receive incoming updates using long polling. + An Array of Update objects is returned. + + Args: + * `bot` - Bot name + * `options` - orddict of options + + Options: + * `:offset` - Identifier of the first update to be returned. Must be greater by one + than the highest among the identifiers of previously received updates. By default, + updates starting with the earliest unconfirmed update are returned. An update is + considered confirmed as soon as `get_updates` is called with an `offset` higher than + its `update_id`. + * `:limit` - Limits the number of updates to be retrieved. Values between 1—100 are + accepted. Defaults to 100 + * `:timeout` - Timeout in seconds for long polling. Defaults to 0, i.e. usual short + polling + """ + @spec get_updates(atom, [{atom, any}]) :: {:ok, [Update.t()]} | {:error, Error.t()} + def get_updates(bot, options \\ []), do: request(bot, "getUpdates", options) + + @doc """ + Use this method to specify a url and receive incoming updates via an outgoing + webhook. Whenever there is an update for the bot, we will send an HTTPS POST + request to the specified url, containing a JSON-serialized Update. In case of + an unsuccessful request, we will give up after a reasonable amount of attempts. + + Args: + * `bot` - Bot name + * `options` - orddict of options + + Options: + * `:url` - HTTPS url to send updates to. + """ + @spec set_webhook(atom, [{atom, any}]) :: :ok | {:error, Error.t()} + def set_webhook(bot, options \\ []), do: request(bot, "setWebhook", options) + + @doc """ + Use this method to remove webhook integration if you decide to switch back to `Nadia.get_updates/1`. + Returns `:ok` on success. + + Args: + * `bot` - Bot name + """ + @spec delete_webhook(atom) :: :ok | {:error, Error.t()} + def delete_webhook(bot), do: request(bot, "deleteWebhook") + + @doc """ + Use this method to get current webhook status. Requires no parameters. + On success, returns a `Nadia.Model.WebhookInfo.t()` object with webhook details. + If the bot is using getUpdates, will return an object with the url field empty. + + Args: + * `bot` - Bot name + """ + @spec get_webhook_info(atom) :: {:ok, WebhookInfo.t()} | {:error, Error.t()} + def get_webhook_info(bot), do: request(bot, "getWebhookInfo") + + @doc """ + Use this method to get basic info about a file and prepare it for downloading. + For the moment, bots can download files of up to 20MB in size. + On success, a File object is returned. + The file can then be downloaded via the link + `https://api.telegram.org/file/bot/`, where is taken + from the response. It is guaranteed that the link will be valid for at least 1 hour. + When the link expires, a new one can be requested by calling `get_file` again. + + Args: + * `bot` - Bot name + * `file_id` - File identifier to get info about + """ + @spec get_file(atom, binary) :: {:ok, File.t()} | {:error, Error.t()} + def get_file(bot, file_id), do: request(bot, "getFile", file_id: file_id) + + @doc ~S""" + Use this method to get link for file for subsequent use. + This method is an extension of the `get_file` method. + + iex> Nadia.get_file_link(%Nadia.Model.File{file_id: "BQADBQADBgADmEjsA1aqdSxtzvvVAg", + ...> file_path: "document/file_10", file_size: 17680}) + {:ok, + "https://api.telegram.org/file/bot#{Nadia.Config.token()}/document/file_10"} + + Args: + * `bot` - Bot name + * `file` - Nadia.Model.File + """ + @spec get_file_link(atom, File.t()) :: {:ok, binary} | {:error, Error.t()} + def get_file_link(bot, file) do + {:ok, build_file_url(bot, file.file_path)} + end + + @doc """ + Use this method to kick a user from a group or a supergroup. In the case of supergroups, + the user will not be able to return to the group on their own using invite links, etc., + unless unbanned first. The bot must be an administrator in the group for this to work. + Returns True on success. + + Note: This will method only work if the ‘All Members Are Admins’ setting is off in the + target group. Otherwise members may only be removed by the group's creator or by the + member that added them. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target group or username of the target supergroup + (in the format @supergroupusername) + * `user_id` - Unique identifier of the target user + """ + @spec kick_chat_member(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + def kick_chat_member(bot, chat_id, user_id) do + request(bot, "kickChatMember", chat_id: chat_id, user_id: user_id) + end + + @doc """ + Use this method for your bot to leave a group, supergroup or channel. + Returns True on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target supergroup or + channel (in the format @supergroupusername) + """ + @spec leave_chat(atom, integer | binary) :: :ok | {:error, Error.t()} + def leave_chat(bot, chat_id) do + request(bot, "leaveChat", chat_id: chat_id) + end + + @doc """ + Use this method to unban a previously kicked user in a supergroup. The user will not + return to the group automatically, but will be able to join via link, etc. The bot + must be an administrator in the group for this to work. Returns True on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target group or username of the target supergroup + (in the format @supergroupusername) + * `user_id` - Unique identifier of the target user + """ + @spec unban_chat_member(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + def unban_chat_member(bot, chat_id, user_id) do + request(bot, "unbanChatMember", chat_id: chat_id, user_id: user_id) + end + + @doc """ + Use this method to get up to date information about the chat (current name of + the user for one-on-one conversations, current username of a user, group or channel, etc.) + Returns a Chat object on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target supergroup or + channel (in the format @supergroupusername) + """ + @spec get_chat(atom, integer | binary) :: {:ok, Chat.t()} | {:error, Error.t()} + def get_chat(bot, chat_id) do + request(bot, "getChat", chat_id: chat_id) + end + + @doc """ + Use this method to get a list of administrators in a chat. On success, returns an Array of + ChatMember objects that contains information about all chat administrators except other bots. + If the chat is a group or a supergroup and no administrators were appointed, only the creator + will be returned. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target supergroup or + channel (in the format @channelusername) + """ + @spec get_chat_administrators(atom, integer | binary) :: + {:ok, [ChatMember.t()]} | {:error, Error.t()} + def get_chat_administrators(bot, chat_id) do + request(bot, "getChatAdministrators", chat_id: chat_id) + end + + @doc """ + Use this method to get the number of members in a chat. Returns Int on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target supergroup or + channel (in the format @channelusername) + """ + @spec get_chat_members_count(atom, integer | binary) :: {:ok, integer} | {:error, Error.t()} + def get_chat_members_count(bot, chat_id) do + request(bot, "getChatMembersCount", chat_id: chat_id) + end + + @doc """ + Use this method to get information about a member of a chat. + Returns a ChatMember object on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target supergroup or + channel (in the format @channelusername) + * `user_id` - Unique identifier of the target user + """ + @spec get_chat_member(atom, integer | binary, integer) :: + {:ok, ChatMember.t()} | {:error, Error.t()} + def get_chat_member(bot, chat_id, user_id) do + request(bot, "getChatMember", chat_id: chat_id, user_id: user_id) + end + + @doc """ + Use this method to send answers to callback queries sent from inline keyboards. + The answer will be displayed to the user as a notification at the top of the chat + screen or as an alert. On success, True is returned. + + Args: + * `bot` - Bot name + * `callback_query_id` - Unique identifier for the query to be answered + * `options` - orddict of options + + Options: + * `:text` - Text of the notification. If not specified, nothing will be shown + to the user + * `:show_alert` - If true, an alert will be shown by the client instead of a + notification at the top of the chat screen. Defaults to false. + """ + @spec answer_callback_query(atom, binary, [{atom, any}]) :: :ok | {:error, Error.t()} + def answer_callback_query(bot, callback_query_id, options \\ []) do + request(bot, "answerCallbackQuery", [callback_query_id: callback_query_id] ++ options) + end + + @doc """ + Use this method to edit text messages sent by the bot or via the bot (for inline bots). + On success, the edited Message is returned + + Args: + * `bot` - Bot name + * `chat_id` - Required if inline_message_id is not specified. Unique identifier + for the target chat or username of the target channel (in the format @channelusername) + * `message_id` - Required if inline_message_id is not specified. Unique identifier of + the sent message + * `inline_message_id` - Required if `chat_id` and `message_id` are not specified. + Identifier of the inline message + * `text` - New text of the message + * `options` - orddict of options + + Options: + * `:parse_mode` - Send Markdown or HTML, if you want Telegram apps to show bold, italic, + fixed-width text or inline URLs in your bot's message. + * `:disable_web_page_preview` - Disables link previews for links in this message + * `:reply_markup` - A JSON-serialized object for an inline + keyboard - `Nadia.Model.InlineKeyboardMarkup` + """ + @spec edit_message_text(atom, integer | binary, integer, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def edit_message_text(bot, chat_id, message_id, inline_message_id, text, options \\ []) do + request( + bot, + "editMessageText", + [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id, text: text] ++ + options + ) + end + + @doc """ + Use this method to delete message from a chat. + Bot should have admin permission to do that, and remember you can't delete messages that are more than + 48 hours old. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `message_id` - Required if inline_message_id is not specified. Unique identifier of + the sent message + """ + @spec delete_message(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + def delete_message(bot, chat_id, message_id) do + request( + bot, + "deleteMessage", + chat_id: chat_id, + message_id: message_id + ) + end + + @doc """ + Use this method to edit captions of messages sent by the bot or via + the bot (for inline bots). On success, the edited Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Required if inline_message_id is not specified. Unique identifier + for the target chat or username of the target channel (in the format @channelusername) + * `message_id` - Required if inline_message_id is not specified. Unique identifier of + the sent message + * `inline_message_id` - Required if `chat_id` and `message_id` are not specified. + Identifier of the inline message + * `options` - orddict of options + + Options: + * `:caption` - New caption of the message + * `:reply_markup` - A JSON-serialized object for an inline + keyboard - `Nadia.Model.InlineKeyboardMarkup` + """ + @spec edit_message_caption(atom, integer | binary, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def edit_message_caption(bot, chat_id, message_id, inline_message_id, options \\ []) do + request( + bot, + "editMessageCaption", + [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options + ) + end + + @doc """ + Use this method to edit only the reply markup of messages sent by the bot or via + the bot (for inline bots). On success, the edited Message is returned. + + Args: + * `bot` - Bot name + * `chat_id` - Required if inline_message_id is not specified. Unique identifier + for the target chat or username of the target channel (in the format @channelusername) + * `message_id` - Required if inline_message_id is not specified. Unique identifier of + the sent message + * `inline_message_id` - Required if `chat_id` and `message_id` are not specified. + Identifier of the inline message + * `options` - orddict of options + + Options: + * `:reply_markup` - A JSON-serialized object for an inline + keyboard - `Nadia.Model.InlineKeyboardMarkup` + """ + @spec edit_message_reply_markup(atom, integer | binary, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + def edit_message_reply_markup(bot, chat_id, message_id, inline_message_id, options \\ []) do + request( + bot, + "editMessageReplyMarkup", + [chat_id: chat_id, message_id: message_id, inline_message_id: inline_message_id] ++ options + ) + end + + @doc """ + Use this method to send answers to an inline query. On success, True is returned. + No more than 50 results per query are allowed. + + Args: + * `bot` - Bot name + * `inline_query_id` - Unique identifier for the answered query + * `results` - An array of results for the inline query + * `options` - orddict of options + + Options: + * `cache_time` - The maximum amount of time in seconds that the result of the inline + query may be cached on the server. Defaults to 300. + * `is_personal` - Pass True, if results may be cached on the server side only for + the user that sent the query. By default, results may be returned to any user who + sends the same query + * `next_offset` - Pass the offset that a client should send in the next query with + the same text to receive more results. Pass an empty string if there are no more + results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. + * `switch_pm_text` - If passed, clients will display a button with specified text + that switches the user to a private chat with the bot and sends the bot a start + message with the parameter switch_pm_parameter. + * `switch_pm_parameter` - Parameter for the start message sent to the bot when user + presses the switch button. + """ + @spec answer_inline_query(atom, binary, [Nadia.Model.InlineQueryResult.t()], [{atom, any}]) :: + :ok | {:error, Error.t()} + def answer_inline_query(bot, inline_query_id, results, options \\ []) do + encoded_results = + results + |> Enum.map(fn result -> + for {k, v} <- Map.from_struct(result), v != nil, into: %{}, do: {k, v} + end) + |> Jason.encode!() + + args = [inline_query_id: inline_query_id, results: encoded_results] + + request(bot, "answerInlineQuery", args ++ options) + end + + @doc """ + Use this method to get a sticker set. On success, a StickerSet object is returned. + + Args: + * `bot` - Bot name + * `name` - Name of the sticker set + """ + @spec get_sticker_set(atom, binary) :: {:ok, Nadia.Model.StickerSet.t()} | {:error, Error.t()} + def get_sticker_set(bot, name) do + request(bot, "getStickerSet", name: name) + end + + @doc """ + Use this method to upload a .png file with a sticker for later use in + createNewStickerSet and addStickerToSet methods (can be used multiple times). + Returns the uploaded File on success. + + Args: + * `bot` - Bot name + * `user_id` - User identifier of sticker file owner + * `png_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. + Either a `file_id` to resend a file that is already on the Telegram servers, + or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file + from the internet. + """ + @spec upload_sticker_file(atom, integer, binary) :: {:ok, File.t()} | {:error, Error.t()} + def upload_sticker_file(bot, user_id, png_sticker) do + request(bot, "uploadStickerFile", [user_id: user_id, png_sticker: png_sticker], :png_sticker) + end + + @doc """ + Use this method to create new sticker set owned by a user. The bot will be able to + edit the created sticker set. Returns True on success. + + Args: + * `bot` - Bot name + * `user_id` - User identifier of created sticker set owner + * `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_”. + is case insensitive. 1-64 characters. + * `title` - Sticker set title, 1-64 characters + * `png_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. + Either a `file_id` to resend a file that is already on the Telegram servers, + or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file + from the internet. + * `emojis` - One or more emoji corresponding to the sticker + + Options: + * `contains_masks` - Pass True, if a set of mask stickers should be created + * `mask_position` - A `Nadia.Model.MaskPosition` object for position where the mask + should be placed on faces + """ + @spec create_new_sticker_set(atom, integer, binary, binary, binary, binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + def create_new_sticker_set(bot, user_id, name, title, png_sticker, emojis, options \\ []) do + request( + bot, + "createNewStickerSet", + [user_id: user_id, name: name, title: title, png_sticker: png_sticker, emojis: emojis] ++ + options, + :png_sticker + ) + end + + @doc """ + Use this method to add a new sticker to a set created by the bot. Returns True on success. + + Args: + * `bot` - Bot name + * `user_id` - User identifier of created sticker set owner + * `name` - Sticker set name + * `png_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. + Either a `file_id` to resend a file that is already on the Telegram servers, + or a `file_path` to upload a new file from local, or a `HTTP URL` to get a file + from the internet. + * `emojis` - One or more emoji corresponding to the sticker + + Options: + * `mask_position` - A `Nadia.Model.MaskPosition` object for position where the mask + should be placed on faces + """ + @spec add_sticker_to_set(atom, integer, binary, binary, binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + def add_sticker_to_set(bot, user_id, name, png_sticker, emojis, options \\ []) do + request( + bot, + "addStickerToSet", + [user_id: user_id, name: name, png_sticker: png_sticker, emojis: emojis] ++ options, + :png_sticker + ) + end + + @doc """ + Use this method to move a sticker in a set created by the bot to a specific position. + Returns True on success. + + Args: + * `bot` - Bot name + * `sticker` - File identifier of the sticker + * `position` - New sticker position in the set, zero-based + """ + @spec set_sticker_position_in_set(atom, binary, integer) :: :ok | {:error, Error.t()} + def set_sticker_position_in_set(bot, sticker, position) do + request(bot, "setStickerPositionInSet", sticker: sticker, position: position) + end + + @doc """ + Use this method to delete a sticker from a set created by the bot. Returns True on success. + + Args: + * `bot` - Bot name + * `sticker` - File identifier of the sticker + """ + @spec delete_sticker_from_set(atom, binary) :: :ok | {:error, Error.t()} + def delete_sticker_from_set(bot, sticker) do + request(bot, "deleteStickerFromSet", sticker: sticker) + end + + @doc """ + Use this method to pin a message in a group, a supergroup, or a channel. The bot must be an + administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right + in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + * `message_id` - Identifier of a message to pin + + Options: + * `disable_notification` - Pass True, if it is not necessary to send a notification to all + chat members about the new pinned message. Notifications are always disabled in channels. + """ + @spec pin_chat_message(atom, integer | binary, integer | binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + def pin_chat_message(bot, chat_id, message_id, options \\ []) do + request(bot, "pinChatMessage", [chat_id: chat_id, message_id: message_id] ++ options) + end + + @doc """ + Use this method to unpin a message in a group, a supergroup, or a channel. The bot must be an + administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in + the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success. + + Args: + * `bot` - Bot name + * `chat_id` - Unique identifier for the target chat or username of the target channel + (in the format @channelusername) + """ + @spec unpin_chat_message(atom, integer | binary) :: :ok | {:error, Error.t()} + def unpin_chat_message(bot, chat_id) do + request(bot, "unpinChatMessage", chat_id: chat_id) + end +end diff --git a/lib/nadia/bot/api.ex b/lib/nadia/bot/api.ex new file mode 100644 index 0000000..eaa36fa --- /dev/null +++ b/lib/nadia/bot/api.ex @@ -0,0 +1,138 @@ +defmodule Nadia.Bot.API do + @moduledoc """ + Provides basic functionalities for Telegram Bot API. + """ + + alias Nadia.Model.Error + alias Nadia.Bot.Config + + defp build_url(bot, method), do: Config.base_url(bot) <> Config.token(bot) <> "/" <> method + + defp process_response(response, method) do + case decode_response(response) do + {:ok, true} -> :ok + {:ok, %{ok: false, description: description}} -> {:error, %Error{reason: description}} + {:ok, result} -> {:ok, Nadia.Parser.parse_result(result, method)} + {:error, %HTTPoison.Error{reason: reason}} -> {:error, %Error{reason: reason}} + {:error, error} -> {:error, %Error{reason: error}} + end + end + + defp decode_response(response) do + with {:ok, %HTTPoison.Response{body: body}} <- response, + {:ok, %{result: result}} <- Jason.decode(body, keys: :atoms), + do: {:ok, result} + end + + defp build_multipart_request(params, file_field) do + {file_path, params} = Keyword.pop(params, file_field) + params = for {k, v} <- params, do: {to_string(k), v} + + {:multipart, + params ++ + [ + {:file, file_path, + {"form-data", [{"name", to_string(file_field)}, {"filename", file_path}]}, []} + ]} + end + + defp calculate_timeout(bot, options) when is_list(options) do + (Keyword.get(options, :timeout, 0) + Config.recv_timeout(bot)) * 1000 + end + + defp calculate_timeout(bot, options) when is_map(options) do + (Map.get(options, :timeout, 0) + Config.recv_timeout(bot)) * 1000 + end + + defp build_request(params, file_field) when is_list(params) do + params + |> Keyword.update(:reply_markup, nil, &Jason.encode!(&1)) + |> map_params(file_field) + end + + defp build_request(params, file_field) when is_map(params) do + params + |> Map.update(:reply_markup, nil, &Jason.encode!(&1)) + |> map_params(file_field) + end + + defp map_params(params, file_field) do + params = + params + |> Enum.filter(fn {_, v} -> v end) + |> Enum.map(fn {k, v} -> {k, to_string(v)} end) + + if !is_nil(file_field) and File.exists?(params[file_field]) do + build_multipart_request(params, file_field) + else + {:form, params} + end + end + + defp build_options(bot, options) do + timeout = calculate_timeout(bot, options) + opts = [recv_timeout: timeout] + + opts = + case Config.proxy(bot) do + proxy when byte_size(proxy) > 0 -> Keyword.put(opts, :proxy, proxy) + proxy when is_tuple(proxy) and tuple_size(proxy) == 3 -> Keyword.put(opts, :proxy, proxy) + _ -> opts + end + + opts = + case Config.proxy_auth(bot) do + proxy_auth when is_tuple(proxy_auth) and tuple_size(proxy_auth) == 2 -> + Keyword.put(opts, :proxy_auth, proxy_auth) + + _ -> + opts + end + + opts = + case Config.socks5_user(bot) do + socks5_user when byte_size(socks5_user) > 0 -> + Keyword.put(opts, :socks5_user, socks5_user) + + _ -> + opts + end + + case Config.socks5_pass(bot) do + socks5_pass when byte_size(socks5_pass) > 0 -> Keyword.put(opts, :socks5_pass, socks5_pass) + _ -> opts + end + end + + @doc """ + Generic method to call Telegram Bot API. + + Args: + * `bot` - name of bot + * `method` - name of API method + * `options` - orddict of options + * `file_field` - specify the key of file_field in `options` when sending files + """ + @spec request(atom, binary, [{atom, any}], atom) :: :ok | {:error, Error.t()} | {:ok, any} + def request(bot, method, options \\ [], file_field \\ nil) do + build_url(bot, method) + |> HTTPoison.post(build_request(options, file_field), [], build_options(bot, options)) + |> process_response(method) + end + + def request?(bot, method, options \\ [], file_field \\ nil) do + {_, response} = request(bot, method, options, file_field) + response + end + + @doc ~S""" + Use this function to build file url. + + iex> Nadia.API.build_file_url("document/file_10") + "https://api.telegram.org/file/bot#{Nadia.Config.token()}/document/file_10" + """ + @spec build_file_url(atom, binary) :: binary + def build_file_url(bot, file_path) do + Config.file_base_url(bot) <> Config.token(bot) <> "/" <> file_path + end +end diff --git a/lib/nadia/bot/behaviour.ex b/lib/nadia/bot/behaviour.ex new file mode 100644 index 0000000..1059586 --- /dev/null +++ b/lib/nadia/bot/behaviour.ex @@ -0,0 +1,69 @@ +defmodule Nadia.Bot.Behaviour do + alias Nadia.Model.{User, Message, Update, UserProfilePhotos, File, Error} + + @callback get_me(atom) :: {:ok, Message.t()} | {:error, Error.t()} + @callback send_message(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback forward_message(atom, integer, integer, integer) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_photo(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_audio(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_document(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_sticker(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_video(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_voice(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_location(atom, integer, float, float, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_venue(atom, integer, float, float, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_contact(atom, integer, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback send_chat_action(atom, integer, binary) :: :ok | {:error, Error.t()} + @callback send_animation(atom, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback get_user_profile_photos(atom, integer, [{atom, any}]) :: + {:ok, UserProfilePhotos.t()} | {:error, Error.t()} + @callback get_updates(atom, [{atom, any}]) :: {:ok, [Update.t()]} | {:error, Error.t()} + @callback set_webhook(atom, [{atom, any}]) :: :ok | {:error, Error.t()} + @callback delete_webhook(atom) :: :ok | {:error, Error.t()} + @callback get_webhook_info(atom) :: {:ok, WebhookInfo.t()} | {:error, Error.t()} + @callback get_file(atom, binary) :: {:ok, File.t()} | {:error, Error.t()} + @callback get_file_link(atom, File.t()) :: {:ok, binary} | {:error, Error.t()} + @callback kick_chat_member(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + @callback leave_chat(atom, integer | binary) :: :ok | {:error, Error.t()} + @callback unban_chat_member(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + @callback get_chat(atom, integer | binary) :: {:ok, Chat.t()} | {:error, Error.t()} + @callback get_chat_administrators(atom, integer | binary) :: + {:ok, [ChatMember.t()]} | {:error, Error.t()} + @callback get_chat_members_count(atom, integer | binary) :: {:ok, integer} | {:error, Error.t()} + @callback get_chat_member(atom, integer | binary, integer) :: + {:ok, ChatMember.t()} | {:error, Error.t()} + @callback answer_callback_query(atom, binary, [{atom, any}]) :: :ok | {:error, Error.t()} + @callback edit_message_text(atom, integer | binary, integer, binary, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback delete_message(atom, integer | binary, integer) :: :ok | {:error, Error.t()} + @callback edit_message_caption(atom, integer | binary, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback edit_message_reply_markup(atom, integer | binary, integer, binary, [{atom, any}]) :: + {:ok, Message.t()} | {:error, Error.t()} + @callback answer_inline_query(atom, binary, [Nadia.Model.InlineQueryResult.t()], [{atom, any}]) :: + :ok | {:error, Error.t()} + @callback get_sticker_set(atom, binary) :: + {:ok, Nadia.Model.StickerSet.t()} | {:error, Error.t()} + @callback upload_sticker_file(atom, integer, binary) :: {:ok, File.t()} | {:error, Error.t()} + @callback create_new_sticker_set(atom, integer, binary, binary, binary, binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + @callback add_sticker_to_set(atom, integer, binary, binary, binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + @callback set_sticker_position_in_set(atom, binary, integer) :: :ok | {:error, Error.t()} + @callback delete_sticker_from_set(atom, binary) :: :ok | {:error, Error.t()} + @callback pin_chat_message(atom, integer | binary, integer | binary, [{atom, any}]) :: + :ok | {:error, Error.t()} + @callback unpin_chat_message(atom, integer | binary) :: :ok | {:error, Error.t()} +end diff --git a/lib/nadia/bot/config.ex b/lib/nadia/bot/config.ex new file mode 100644 index 0000000..d87e0b1 --- /dev/null +++ b/lib/nadia/bot/config.ex @@ -0,0 +1,38 @@ +defmodule Nadia.Bot.Config do + @default_timeout 5 + @default_base_url "https://api.telegram.org/bot" + @default_graph_base_url "https://api.telegra.ph" + @default_file_base_url "https://api.telegram.org/file/bot" + + @spec token(atom) :: binary + def token(bot), do: config_or_env(bot, :token) + + @spec proxy(atom) :: binary + def proxy(bot), do: config_or_env(bot, :proxy) + def proxy_auth(bot), do: config_or_env(bot, :proxy_auth) + def socks5_user(bot), do: config_or_env(bot, :socks5_user) + def socks5_pass(bot), do: config_or_env(bot, :socks5_pass) + def recv_timeout(bot), do: config_or_env(bot, :recv_timeout) || @default_timeout + def base_url(bot), do: config_or_env(bot, :base_url) || @default_base_url + def graph_base_url(bot), do: config_or_env(bot, :graph_base_url) || @default_graph_base_url + def file_base_url(bot), do: config_or_env(bot, :file_base_url) || @default_file_base_url + + defp config_or_env(bot, key) do + case Application.fetch_env(bot, key) do + {:ok, {:system, var}} -> + System.get_env(var) + + {:ok, {:system, var, default}} -> + case System.get_env(var) do + nil -> default + val -> val + end + + {:ok, value} -> + value + + :error -> + nil + end + end +end diff --git a/lib/nadia/bot/graph_api.ex b/lib/nadia/bot/graph_api.ex new file mode 100644 index 0000000..25c8547 --- /dev/null +++ b/lib/nadia/bot/graph_api.ex @@ -0,0 +1,68 @@ +defmodule Nadia.Bot.GraphAPI do + @moduledoc """ + Provides basic functionalities for Telegram Bot API. + """ + + alias Nadia.Graph.Model.Error + alias Nadia.Bot.Config + + defp build_url(bot, method), do: Config.graph_base_url(bot) <> "/" <> method + + defp process_response(response, method) do + case decode_response(response) do + {:ok, true} -> :ok + {:ok, result} -> {:ok, Nadia.Graph.Parser.parse_result(result, method)} + %{ok: false, description: description} -> {:error, %Error{reason: description}} + {:error, %HTTPoison.Error{reason: reason}} -> {:error, %Error{reason: reason}} + end + end + + defp decode_response(response) do + with {:ok, %HTTPoison.Response{body: body}} <- response, + %{result: result} <- Jason.decode!(body, keys: :atoms), + do: {:ok, result} + end + + defp build_multipart_request(params, file_field) do + {file_path, params} = Keyword.pop(params, file_field) + params = for {k, v} <- params, do: {to_string(k), v} + + {:multipart, + params ++ + [ + {:file, file_path, + {"form-data", [{"name", to_string(file_field)}, {"filename", file_path}]}, []} + ]} + end + + defp build_request(params, file_field) do + params = + params + |> Keyword.update(:reply_markup, nil, &Jason.encode!(&1)) + |> Stream.filter(fn {_, v} -> v end) + |> Enum.map(fn {k, v} -> {k, to_string(v)} end) + + if !is_nil(file_field) and File.exists?(params[file_field]) do + build_multipart_request(params, file_field) + else + {:form, params} + end + end + + @doc """ + Generic method to call Telegram Bot API. + + Args: + * `bot` - name of the bot + * `method` - name of API method + * `options` - orddict of options + * `file_field` - specify the key of file_field in `options` when sending files + """ + def request(bot, method, options \\ [], file_field \\ nil) do + timeout = (Keyword.get(options, :timeout, 0) + Config.recv_timeout(bot)) * 1000 + + build_url(bot, method) + |> HTTPoison.post(build_request(options, file_field), [], recv_timeout: timeout) + |> process_response(method) + end +end diff --git a/lib/nadia/bot_graph.ex b/lib/nadia/bot_graph.ex new file mode 100644 index 0000000..6721a28 --- /dev/null +++ b/lib/nadia/bot_graph.ex @@ -0,0 +1,176 @@ +defmodule Nadia.BotGraph do + @moduledoc """ + Provides access to Telegra.ph API. + + ## Reference + http://telegra.ph/api + """ + + alias Nadia.Graph.Model.{Account, Error} + + import Nadia.Bot.GraphAPI + + @doc """ + Use this method to create a new Telegraph account. Most users only need one account, but this can be useful for channel administrators who would like to keep individual author names and profile links for each of their channels. On success, returns an Account object with the regular fields and an additional access_token field. + + Args: + * `bot` - Bot name + * `short_name` - account name, helps users with several accounts remember which they are currently using. Displayed to the user above the "Edit/Publish" button on Telegra.ph, other users don't see this name. 1-32 characters + * `author_name` - default author name used when creating new articles. 0-128 characters + * `options` - orddict of options + + Options: + * `:author_url` - default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channel. 0-512 characters + """ + @spec create_account(atom, binary, binary, [{atom, any}]) :: + {:ok, Account.t()} | {:error, Error.t()} + def create_account(bot, short_name, author_name, options \\ []) do + request(bot, "createAccount", [short_name: short_name, author_name: author_name] ++ options) + end + + @doc """ + Use this method to update information about a Telegraph account. Pass only the parameters that you want to edit. On success, returns an Account object with the default fields. + + Args: + * `bot` - Bot name + * `access_token` - access token of the Telegraph account + * `short_name` - new account name. 1-32 characters + * `author_name` - new default author name used when creating new articles. 0-128 characters + * `options` - orddict of options + + Options: + * `:author_url` - new default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channel. 0-512 characters + """ + @spec edit_account_info(atom, binary, binary, binary, [{atom, any}]) :: + {:ok, Account.t()} | {:error, Error.t()} + def edit_account_info(bot, access_token, short_name, author_name, options \\ []) do + request( + bot, + "editAccountInfo", + [access_token: access_token, short_name: short_name, author_name: author_name] ++ options + ) + end + + @doc """ + Use this method to get information about a Telegraph account. Returns an Account object on success. + + Args: + * `bot` - Bot name + * `access_token` - access token of the Telegraph account + * `fields` - list of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count + """ + @spec get_account_info(atom, binary, [binary]) :: {:ok, Account.t()} | {:error, Error.t()} + def get_account_info(bot, access_token, fields \\ ["short_name", "author_name", "author_url"]) do + request(bot, "getAccountInfo", access_token: access_token, fields: fields) + end + + @doc """ + Use this method to revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns an Account object with new access_token and auth_url fields. + + Args: + * `bot` - Bot name + * `access_token` - access token of the Telegraph account + """ + @spec revoke_access_token(atom, binary) :: {:ok, Account.t()} | {:error, Error.t()} + def revoke_access_token(bot, access_token) do + request(bot, "revokeAccessToken", access_token: access_token) + end + + @doc """ + Use this method to get a list of pages belonging to a Telegraph account. Returns a PageList object, sorted by most recently created pages first. + + Args: + * `bot` - Bot name + * `access_token` - access token of the Telegraph account + * `offset` - sequential number of the first page to be returned + * `limit` - limits the number of pages to be retrieved. 0-200 + """ + @spec get_page_list(atom, binary, integer, integer) :: + {:ok, [[PageList.t()]]} | {:error, Error.t()} + def get_page_list(bot, access_token, offset \\ 0, limit \\ 50) do + request(bot, "getPageList", access_token: access_token, offset: offset, limit: limit) + end + + @doc """ + Use this method to create a new Telegraph page. On success, returns a Page object. + + Args: + * `bot` - Bot name + * `access_token` - (String) Access token of the Telegraph account. + * `title` - (String, 1-256 characters) Page title. + * `content` - (Array of Node, up to 64 KB)` Content of the page. + * `options` - orddict of options + + Options: + * `:author_name` - (String, 0-128 characters) Author name, displayed below the article's title. + * `:author_url` - (String, 0-512 characters) Profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channel. + * `:return_content` - (Boolean, default = false) If true, a content field will be returned in the Page object (see: Content format). + """ + @spec create_page(atom, binary, binary, binary, [{atom, any}]) :: + {:ok, Page.t()} | {:error, Error.t()} + def create_page(bot, access_token, title, content, options \\ []) do + request( + bot, + "createPage", + [access_token: access_token, title: title, content: content] ++ options + ) + end + + @doc """ + Use this method to edit an existing Telegraph page. On success, returns a Page object. + + Args: + * `bot` - Bot name + * `access_token` - (String) Access token of the Telegraph account. + * `path` - (String) Path to the page. + * `title` - (String, 1-256 characters) Page title. + * `content` - (Array of Node, up to 64 KB) Content of the page. + * `options` - orddict of options + + Options: + * `:author_name` - (String, 0-128 characters) Author name, displayed below the article's title. + * `:author_url` - (String, 0-512 characters) Profile link, opened when users click on the author's * `:name below` - the title. Can be any link, not necessarily to a Telegram profile or channel. + * `:return_content` - (Boolean, default = false) If true, a content field will be returned in the Page object. + """ + @spec edit_page(atom, binary, binary, binary, binary, [{atom, any}]) :: + {:ok, Page.t()} | {:error, Error.t()} + def edit_page(bot, access_token, path, title, content, options \\ []) do + request( + bot, + "editPage/" <> path, + [access_token: access_token, title: title, content: content] ++ options + ) + end + + @doc """ + Use this method to get a Telegraph page. Returns a Page object on success. + + Args: + * `bot` - Bot name + * `path` path to the Telegraph page (in the format Title-12-31, i.e. everything that comes after http://telegra.ph/) + * `return_content` - if true, content field will be returned in Page object + """ + @spec get_page(atom, binary, [atom]) :: {:ok, Page.t()} | {:error, Error.t()} + def get_page(bot, path, return_content \\ true) do + request(bot, "getPage/" <> path, return_content: return_content) + end + + @doc """ + Use this method to get the number of views for a Telegraph article. Returns a PageViews object on success. By default, the total number of page views will be returned. + + Args: + * `bot` - Bot name + * `path` - path to the Telegraph page (in the format Title-12-31, where 12 is the month and 31 the day the article was first published) + * `filter_fields` - orddict of fields + + Filter fields: + * `:year` - if passed, the number of page views for the requested year will be returned. + * `:month` - if passed, the number of page views for the requested month will be returned + * `:day` - if passed, the number of page views for the requested day will be returned. + * `:hour` - if passed, the number of page views for the requested hour will be returned. + """ + @spec get_views(atom, binary, [{atom, any}]) :: {:ok, PageViews.t()} | {:error, Error.t()} + def get_views(bot, path, filter_fields) do + request(bot, "getViews/" <> path, filter_fields) + end +end diff --git a/lib/nadia/config.ex b/lib/nadia/config.ex index 6f097ef..1f44804 100644 --- a/lib/nadia/config.ex +++ b/lib/nadia/config.ex @@ -1,35 +1,30 @@ defmodule Nadia.Config do - @default_timeout 5 - @default_base_url "https://api.telegram.org/bot" - @default_graph_base_url "https://api.telegra.ph" - @default_file_base_url "https://api.telegram.org/file/bot" - - def token, do: config_or_env(:token) - def proxy, do: config_or_env(:proxy) - def proxy_auth, do: config_or_env(:proxy_auth) - def socks5_user, do: config_or_env(:socks5_user) - def socks5_pass, do: config_or_env(:socks5_pass) - def recv_timeout, do: config_or_env(:recv_timeout) || @default_timeout - def base_url, do: config_or_env(:base_url) || @default_base_url - def graph_base_url, do: config_or_env(:graph_base_url) || @default_graph_base_url - def file_base_url, do: config_or_env(:file_base_url) || @default_file_base_url - - defp config_or_env(key) do - case Application.fetch_env(:nadia, key) do - {:ok, {:system, var}} -> - System.get_env(var) - - {:ok, {:system, var, default}} -> - case System.get_env(var) do - nil -> default - val -> val - end - - {:ok, value} -> - value - - :error -> - nil - end - end + alias Nadia.Bot.Config + + @spec token :: binary + def token, do: Config.token(:nadia) + + @spec proxy :: binary + def proxy, do: Config.proxy(:nadia) + + @spec proxy_auth :: binary + def proxy_auth, do: Config.proxy_auth(:nadia) + + @spec socks5_user :: binary + def socks5_user, do: Config.socks5_user(:nadia) + + @spec socks5_pass :: binary + def socks5_pass, do: Config.socks5_pass(:nadia) + + @spec recv_timeout :: binary + def recv_timeout, do: Config.recv_timeout(:nadia) + + @spec base_url :: binary + def base_url, do: Config.base_url(:nadia) + + @spec graph_base_url :: binary + def graph_base_url, do: Config.graph_base_url(:nadia) + + @spec file_base_url :: binary + def file_base_url, do: Config.file_base_url(:nadia) end diff --git a/lib/nadia/graph.ex b/lib/nadia/graph.ex index c43c6a3..b7e3e00 100644 --- a/lib/nadia/graph.ex +++ b/lib/nadia/graph.ex @@ -8,7 +8,7 @@ defmodule Nadia.Graph do alias Nadia.Graph.Model.{Account, Error} - import Nadia.Graph.API + alias Nadia.BotGraph @doc """ Use this method to create a new Telegraph account. Most users only need one account, but this can be useful for channel administrators who would like to keep individual author names and profile links for each of their channels. On success, returns an Account object with the regular fields and an additional access_token field. @@ -22,9 +22,8 @@ defmodule Nadia.Graph do * `:author_url` - default profile link, opened when users click on the author's name below the title. Can be any link, not necessarily to a Telegram profile or channel. 0-512 characters """ @spec create_account(binary, binary, [{atom, any}]) :: {:ok, Account.t()} | {:error, Error.t()} - def create_account(short_name, author_name, options \\ []) do - request("createAccount", [short_name: short_name, author_name: author_name] ++ options) - end + def create_account(short_name, author_name, options \\ []), + do: BotGraph.create_account(:nadia, short_name, author_name, options) @doc """ Use this method to update information about a Telegraph account. Pass only the parameters that you want to edit. On success, returns an Account object with the default fields. @@ -39,12 +38,8 @@ defmodule Nadia.Graph do """ @spec edit_account_info(binary, binary, binary, [{atom, any}]) :: {:ok, Account.t()} | {:error, Error.t()} - def edit_account_info(access_token, short_name, author_name, options \\ []) do - request( - "editAccountInfo", - [access_token: access_token, short_name: short_name, author_name: author_name] ++ options - ) - end + def edit_account_info(access_token, short_name, author_name, options \\ []), + do: BotGraph.edit_account_info(:nadia, access_token, short_name, author_name, options) @doc """ Use this method to get information about a Telegraph account. Returns an Account object on success. @@ -53,9 +48,8 @@ defmodule Nadia.Graph do * `fields` - list of account fields to return. Available fields: short_name, author_name, author_url, auth_url, page_count """ @spec get_account_info(binary, [binary]) :: {:ok, Account.t()} | {:error, Error.t()} - def get_account_info(access_token, fields \\ ["short_name", "author_name", "author_url"]) do - request("getAccountInfo", access_token: access_token, fields: fields) - end + def get_account_info(access_token, fields \\ ["short_name", "author_name", "author_url"]), + do: BotGraph.get_account_info(:nadia, access_token, fields) @doc """ Use this method to revoke access_token and generate a new one, for example, if the user would like to reset all connected sessions, or you have reasons to believe the token was compromised. On success, returns an Account object with new access_token and auth_url fields. @@ -63,9 +57,7 @@ defmodule Nadia.Graph do * `access_token` - access token of the Telegraph account """ @spec revoke_access_token(binary) :: {:ok, Account.t()} | {:error, Error.t()} - def revoke_access_token(access_token) do - request("revokeAccessToken", access_token: access_token) - end + def revoke_access_token(access_token), do: BotGraph.revoke_access_token(:nadia, access_token) @doc """ Use this method to get a list of pages belonging to a Telegraph account. Returns a PageList object, sorted by most recently created pages first. @@ -75,9 +67,8 @@ defmodule Nadia.Graph do * `limit` - limits the number of pages to be retrieved. 0-200 """ @spec get_page_list(binary, integer, integer) :: {:ok, [[PageList.t()]]} | {:error, Error.t()} - def get_page_list(access_token, offset \\ 0, limit \\ 50) do - request("getPageList", access_token: access_token, offset: offset, limit: limit) - end + def get_page_list(access_token, offset \\ 0, limit \\ 50), + do: BotGraph.get_page_list(:nadia, access_token, offset, limit) @doc """ Use this method to create a new Telegraph page. On success, returns a Page object. @@ -95,9 +86,8 @@ defmodule Nadia.Graph do """ @spec create_page(binary, binary, binary, [{atom, any}]) :: {:ok, Page.t()} | {:error, Error.t()} - def create_page(access_token, title, content, options \\ []) do - request("createPage", [access_token: access_token, title: title, content: content] ++ options) - end + def create_page(access_token, title, content, options \\ []), + do: BotGraph.create_page(:nadia, access_token, title, content, options) @doc """ Use this method to edit an existing Telegraph page. On success, returns a Page object. @@ -115,12 +105,8 @@ defmodule Nadia.Graph do """ @spec edit_page(binary, binary, binary, binary, [{atom, any}]) :: {:ok, Page.t()} | {:error, Error.t()} - def edit_page(access_token, path, title, content, options \\ []) do - request( - "editPage/" <> path, - [access_token: access_token, title: title, content: content] ++ options - ) - end + def edit_page(access_token, path, title, content, options \\ []), + do: BotGraph.edit_page(:nadia, access_token, path, title, content, options) @doc """ Use this method to get a Telegraph page. Returns a Page object on success. @@ -129,9 +115,7 @@ defmodule Nadia.Graph do * `return_content` - if true, content field will be returned in Page object """ @spec get_page(binary, [atom]) :: {:ok, Page.t()} | {:error, Error.t()} - def get_page(path, return_content \\ true) do - request("getPage/" <> path, return_content: return_content) - end + def get_page(path, return_content \\ true), do: BotGraph.get_page(:nadia, path, return_content) @doc """ Use this method to get the number of views for a Telegraph article. Returns a PageViews object on success. By default, the total number of page views will be returned. @@ -146,7 +130,5 @@ defmodule Nadia.Graph do * `:hour` - if passed, the number of page views for the requested hour will be returned. """ @spec get_views(binary, [{atom, any}]) :: {:ok, PageViews.t()} | {:error, Error.t()} - def get_views(path, filter_fields) do - request("getViews/" <> path, filter_fields) - end + def get_views(path, filter_fields), do: BotGraph.get_views(:nadia, path, filter_fields) end diff --git a/lib/nadia/graph/api.ex b/lib/nadia/graph/api.ex index 13f6542..0801d94 100644 --- a/lib/nadia/graph/api.ex +++ b/lib/nadia/graph/api.ex @@ -3,51 +3,7 @@ defmodule Nadia.Graph.API do Provides basic functionalities for Telegram Bot API. """ - alias Nadia.Graph.Model.Error - alias Nadia.Config - - defp build_url(method), do: Config.graph_base_url() <> "/" <> method - - defp process_response(response, method) do - case decode_response(response) do - {:ok, true} -> :ok - {:ok, result} -> {:ok, Nadia.Graph.Parser.parse_result(result, method)} - %{ok: false, description: description} -> {:error, %Error{reason: description}} - {:error, %HTTPoison.Error{reason: reason}} -> {:error, %Error{reason: reason}} - end - end - - defp decode_response(response) do - with {:ok, %HTTPoison.Response{body: body}} <- response, - %{result: result} <- Jason.decode!(body, keys: :atoms), - do: {:ok, result} - end - - defp build_multipart_request(params, file_field) do - {file_path, params} = Keyword.pop(params, file_field) - params = for {k, v} <- params, do: {to_string(k), v} - - {:multipart, - params ++ - [ - {:file, file_path, - {"form-data", [{"name", to_string(file_field)}, {"filename", file_path}]}, []} - ]} - end - - defp build_request(params, file_field) do - params = - params - |> Keyword.update(:reply_markup, nil, &Jason.encode!(&1)) - |> Stream.filter(fn {_, v} -> v end) - |> Enum.map(fn {k, v} -> {k, to_string(v)} end) - - if !is_nil(file_field) and File.exists?(params[file_field]) do - build_multipart_request(params, file_field) - else - {:form, params} - end - end + alias Nadia.Bot.GraphAPI @doc """ Generic method to call Telegram Bot API. @@ -57,12 +13,6 @@ defmodule Nadia.Graph.API do * `options` - orddict of options * `file_field` - specify the key of file_field in `options` when sending files """ - def request(method, options \\ [], file_field \\ nil) do - timeout = (Keyword.get(options, :timeout, 0) + Config.recv_timeout()) * 1000 - - method - |> build_url - |> HTTPoison.post(build_request(options, file_field), [], recv_timeout: timeout) - |> process_response(method) - end + def request(method, options \\ [], file_field \\ nil), + do: GraphAPI.request(:nadia, method, options, file_field) end