From 5a4afd01d184dc7ef61e73544d8b384900a0044d Mon Sep 17 00:00:00 2001 From: warrially Date: Sat, 25 Jun 2022 11:32:30 +0800 Subject: [PATCH] 1 --- api.chat.go | 50 +++++++++++++++++++ api.message.go | 128 +++++++++++++++++++++++++++++++++++++++++++++++++ api.update.go | 40 ++++++++++++++++ api.user.go | 28 +++++++++++ tg.go | 48 +++++++++++++++++++ 5 files changed, 294 insertions(+) create mode 100644 api.chat.go create mode 100644 api.message.go create mode 100644 api.update.go create mode 100644 api.user.go create mode 100644 tg.go diff --git a/api.chat.go b/api.chat.go new file mode 100644 index 0000000..16763c8 --- /dev/null +++ b/api.chat.go @@ -0,0 +1,50 @@ +package tg + +/*Chat +This object represents a chat. + +Field Type Description +id Integer Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. +type String Type of chat, can be either “private”, “group”, “supergroup” or “channel” +title String Optional. Title, for supergroups, channels and group chats +username String Optional. Username, for private chats, supergroups and channels if available +first_name String Optional. First name of the other party in a private chat +last_name String Optional. Last name of the other party in a private chat +photo ChatPhoto Optional. Chat photo. Returned only in getChat. +bio String Optional. Bio of the other party in a private chat. Returned only in getChat. +has_private_forwards True Optional. True, if privacy settings of the other party in the private chat allows to use tg://user?id= links only in chats with the user. Returned only in getChat. +description String Optional. Description, for groups, supergroups and channel chats. Returned only in getChat. +invite_link String Optional. Primary invite link, for groups, supergroups and channel chats. Returned only in getChat. +pinned_message Message Optional. The most recent pinned message (by sending date). Returned only in getChat. +permissions ChatPermissions Optional. Default chat member permissions, for groups and supergroups. Returned only in getChat. +slow_mode_delay Integer Optional. For supergroups, the minimum allowed delay between consecutive messages sent by each unpriviledged user; in seconds. Returned only in getChat. +message_auto_delete_time Integer Optional. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in getChat. +has_protected_content True Optional. True, if messages from the chat can't be forwarded to other chats. Returned only in getChat. +sticker_set_name String Optional. For supergroups, name of group sticker set. Returned only in getChat. +can_set_sticker_set True Optional. True, if the bot can change the group sticker set. Returned only in getChat. +linked_chat_id Integer Optional. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. Returned only in getChat. +location ChatLocation Optional. For supergroups, the location to which the supergroup is connected. Returned only in getChat. +*/ + +type TChat struct { + ID int `json:"id"` + Type string `json:"type"` + Title string `json:"title"` + Username string `json:"username"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + // Photo ChatPhoto `json:"photo"` + Bio string `json:"bio"` + HasPrivateForwards bool `json:"has_private_forwards"` + Description string `json:"description"` + InviteLink string `json:"invite_link"` + PinnedMessage *TMessage `json:"pinned_message"` + // Permissions ChatPermissions `json:"permissions"` + SlowModeDelay int `json:"slow_mode_delay"` + MessageAutoDeleteTime int `json:"message_auto_delete_time"` + HasProtectedContent bool `json:"has_protected_content"` + StickerSetName string `json:"sticker_set_name"` + CanSetStickerSet bool `json:"can_set_sticker_set"` + LinkedChatId int `json:"linked_chat_id"` + // Location *TChatLocation `json:"location"` +} diff --git a/api.message.go b/api.message.go new file mode 100644 index 0000000..15c2677 --- /dev/null +++ b/api.message.go @@ -0,0 +1,128 @@ +package tg + +/* +Message +This object represents a message. + +Field Type Description +message_id Integer Unique message identifier inside this chat +from User Optional. Sender of the message; empty for messages sent to channels. For backward compatibility, the field contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat. +sender_chat Chat Optional. Sender of the message, sent on behalf of a chat. For example, the channel itself for channel posts, the supergroup itself for messages from anonymous group administrators, the linked channel for messages automatically forwarded to the discussion group. For backward compatibility, the field from contains a fake sender user in non-channel chats, if the message was sent on behalf of a chat. +date Integer Date the message was sent in Unix time +chat Chat Conversation the message belongs to +forward_from User Optional. For forwarded messages, sender of the original message +forward_from_chat Chat Optional. For messages forwarded from channels or from anonymous administrators, information about the original sender chat +forward_from_message_id Integer Optional. For messages forwarded from channels, identifier of the original message in the channel +forward_signature String Optional. For forwarded messages that were originally sent in channels or by an anonymous chat administrator, signature of the message sender if present +forward_sender_name String Optional. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages +forward_date Integer Optional. For forwarded messages, date the original message was sent in Unix time +is_automatic_forward True Optional. True, if the message is a channel post that was automatically forwarded to the connected discussion group +reply_to_message Message Optional. For replies, the original message. Note that the Message object in this field will not contain further reply_to_message fields even if it itself is a reply. +via_bot User Optional. Bot through which the message was sent +edit_date Integer Optional. Date the message was last edited in Unix time +has_protected_content True Optional. True, if the message can't be forwarded +media_group_id String Optional. The unique identifier of a media message group this message belongs to +author_signature String Optional. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator +text String Optional. For text messages, the actual UTF-8 text of the message, 0-4096 characters +entities Array of MessageEntity Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text +animation Animation Optional. Message is an animation, information about the animation. For backward compatibility, when this field is set, the document field will also be set +audio Audio Optional. Message is an audio file, information about the file +document Document Optional. Message is a general file, information about the file +photo Array of PhotoSize Optional. Message is a photo, available sizes of the photo +sticker Sticker Optional. Message is a sticker, information about the sticker +video Video Optional. Message is a video, information about the video +video_note VideoNote Optional. Message is a video note, information about the video message +voice Voice Optional. Message is a voice message, information about the file +caption String Optional. Caption for the animation, audio, document, photo, video or voice, 0-1024 characters +caption_entities Array of MessageEntity Optional. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption +contact Contact Optional. Message is a shared contact, information about the contact +dice Dice Optional. Message is a dice with random value +game Game Optional. Message is a game, information about the game. More about games » +poll Poll Optional. Message is a native poll, information about the poll +venue Venue Optional. Message is a venue, information about the venue. For backward compatibility, when this field is set, the location field will also be set +location Location Optional. Message is a shared location, information about the location +new_chat_members Array of User Optional. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members) +left_chat_member User Optional. A member was removed from the group, information about them (this member may be the bot itself) +new_chat_title String Optional. A chat title was changed to this value +new_chat_photo Array of PhotoSize Optional. A chat photo was change to this value +delete_chat_photo True Optional. Service message: the chat photo was deleted +group_chat_created True Optional. Service message: the group has been created +supergroup_chat_created True Optional. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup. +channel_chat_created True Optional. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel. +message_auto_delete_timer_changed MessageAutoDeleteTimerChanged Optional. Service message: auto-delete timer settings changed in the chat +migrate_to_chat_id Integer Optional. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. +migrate_from_chat_id Integer Optional. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier. +pinned_message Message Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. +invoice Invoice Optional. Message is an invoice for a payment, information about the invoice. More about payments » +successful_payment SuccessfulPayment Optional. Message is a service message about a successful payment, information about the payment. More about payments » +connected_website String Optional. The domain name of the website on which the user has logged in. More about Telegram Login » +passport_data PassportData Optional. Telegram Passport data +proximity_alert_triggered ProximityAlertTriggered Optional. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location. +video_chat_scheduled VideoChatScheduled Optional. Service message: video chat scheduled +video_chat_started VideoChatStarted Optional. Service message: video chat started +video_chat_ended VideoChatEnded Optional. Service message: video chat ended +video_chat_participants_invited VideoChatParticipantsInvited Optional. Service message: new participants invited to a video chat +web_app_data WebAppData Optional. Service message: data sent by a Web App +reply_markup InlineKeyboardMarkup Optional. Inline keyboard attached to the message. login_url buttons are represented as ordinary url buttons. +*/ +type TMessage struct { + Message_id int `json:"message_id"` + From *TUser `json:"from"` + SenderChat *TChat `json:"sender_chat"` + Date int `json:"date"` + Chat *TChat `json:"chat"` + ForwardFrom *TUser `json:"forward_from"` + ForwardFrom_chat *TChat `json:"forward_from_chat"` + ForwardFrom_message_id int `json:"forward_from_message_id"` + ForwardSignature string `json:"forward_signature"` + ForwardSender_name string `json:"forward_sender_name"` + ForwardDate int `json:"forward_date"` + IsAutomaticForward bool `json:"is_automatic_forward"` + ReplyToMessage *TMessage `json:"reply_to_message"` + ViaBot *TUser `json:"via_bot"` + EditDate int `json:"edit_date"` + HasProtected_content bool `json:"has_protected_content"` + MediaGroupID string `json:"media_group_id"` + AuthorSignature string `json:"author_signature"` + Text string `json:"text"` + // Entities *TArray `json:"entities"` + // Animation *TAnimation `json:"animation"` + // Audio *TAudio `json:"audio"` + // Document *TDocument `json:"document"` + // Photo *TArray `json:"photo"` + // Sticker *TSticker `json:"sticker"` + // Video *TVideo `json:"video"` + // VideoNote *TVideoNote `json:"video_note"` + // Voice *TVoice `json:"voice"` + // Caption string `json:"caption"` + // CaptionEntities *TArray `json:"caption_entities"` + // Contact *TContact `json:"contact"` + // Dice *TDice `json:"dice"` + // Game *TGame `json:"game"` + // Poll *TPoll `json:"poll"` + // Venue *TVenue `json:"venue"` + // Location *TLocation `json:"location"` + // NewChatMembers *TArray `json:"new_chat_members"` + // LeftChatMember *TUser `json:"left_chat_member"` + // NewChatTitle string `json:"new_chat_title"` + // NewChatPhoto *TArray `json:"new_chat_photo"` + // DeleteChatPhoto bool `json:"delete_chat_photo"` + // GroupChatCreated bool `json:"group_chat_created"` + // SupergroupChatCreated bool `json:"supergroup_chat_created"` + // ChannelChatCreated bool `json:"channel_chat_created"` + // MessageAutoDeleteTimerChanged *TMessageAutoDeleteTimerChanged `json:"message_auto_delete_timer_changed"` + // MigrateToChatID int `json:"migrate_to_chat_id"` + // MigrateFromChatID int `json:"migrate_from_chat_id"` + // PinnedMessage *TMessage `json:"pinned_message"` + // Invoice *TInvoice `json:"invoice"` + // SuccessfulPayment *TSuccessfulPayment `json:"successful_payment"` + // ConnectedWebsite string `json:"connected_website"` + // PassportData *TPassportData `json:"passport_data"` + // ProximityAlertTriggered *TProximityAlertTriggered `json:"proximity_alert_triggered"` + // VideoChatScheduled *TVideoChatScheduled `json:"video_chat_scheduled"` + // VideoChatStarted *TVideoChatStarted `json:"video_chat_started"` + // VideoChatEnded *TVideoChatEnded `json:"video_chat_ended"` + // VideoChatParticipants_invited *TVideoChatParticipantsInvited `json:"video_chat_participants_invited"` + // WebAppData *TWebAppData `json:"web_app_data"` + // ReplyMarkup *TInlineKeyboardMarkup `json:"reply_markup"` +} diff --git a/api.update.go b/api.update.go new file mode 100644 index 0000000..13d803a --- /dev/null +++ b/api.update.go @@ -0,0 +1,40 @@ +package tg + +// Update +// This object represents an incoming update. +// At most one of the optional parameters can be present in any given update. + +// Field Type Description +// update_id Integer The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially. +// message Message Optional. New incoming message of any kind — text, photo, sticker, etc. +// edited_message Message Optional. New version of a message that is known to the bot and was edited +// channel_post Message Optional. New incoming channel post of any kind — text, photo, sticker, etc. +// edited_channel_post Message Optional. New version of a channel post that is known to the bot and was edited +// inline_query InlineQuery Optional. New incoming inline query +// chosen_inline_result ChosenInlineResult Optional. The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot. +// callback_query CallbackQuery Optional. New incoming callback query +// shipping_query ShippingQuery Optional. New incoming shipping query. Only for invoices with flexible price +// pre_checkout_query PreCheckoutQuery Optional. New incoming pre-checkout query. Contains full information about checkout +// poll Poll Optional. New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot +// poll_answer PollAnswer Optional. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself. +// my_chat_member ChatMemberUpdated Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user. +// chat_member ChatMemberUpdated Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates. +// chat_join_request ChatJoinRequest Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates. + +type TUpdate struct { + UpdateID int `json:"update_id"` // 更新的唯一标识符。更新标识符从某个正数开始,并按顺序递增。如果您使用的是Webhook,则此ID变得特别方便,因为它允许您忽略重复的更新或恢复正确的更新序列,如果它们出现故障。如果至少一周内没有新更新,则将随机选择下一次更新的标识符,而不是按顺序选择。 + Message *TMessage `json:"message"` + EditedMessage *TMessage `json:"edited_message"` + ChannelPost *TMessage `json:"channel_post"` + EditedChannelPost *TMessage `json:"edited_channel_post"` + // InlineQuery *TInlineQuery `json:"inline_query"` + // ChosenInlineResult *TChosenInlineResult `json:"chosen_inline_result"` + // CallbackQuery *TCallbackQuery `json:"callback_query"` + // ShippingQuer *TShippingQuery `json:"shipping_query"` + // PreCheckoutQuery *TPreCheckoutQuery `json:"pre_checkout_query"` + // Poll *TPoll `json:"poll"` + // PollAnswer *TPollAnswer `json:"poll_answer"` + // MyChatMember *TChatMemberUpdated `json:"my_chat_member"` + // ChatMember *TChatMemberUpdated `json:"chat_member"` + // ChatJoinRequest *TChatJoinRequest `json:"chat_join_request"` +} diff --git a/api.user.go b/api.user.go new file mode 100644 index 0000000..ff0c2f7 --- /dev/null +++ b/api.user.go @@ -0,0 +1,28 @@ +package tg + +/* +User +This object represents a Telegram user or bot. + +Field Type Description +id in Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. +is_bot Boolean True, if this user is a bot +first_name string User's or bot's first name +last_name String Optional. User's or bot's last name +username String Optional. User's or bot's username +language_code String Optional. IETF language tag of the user's language +can_join_groups Boolean Optional. True, if the bot can be invited to groups. Returned only in getMe. +can_read_all_group_messages Boolean Optional. True, if privacy mode is disabled for the bot. Returned only in getMe. +supports_inline_queries Boolean Optional. True, if the bot supports inline queries. Returned only in getMe. +*/ +type TUser struct { + ID int `json:"id"` + IsBot bool `json:"is_bot"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Username string `json:"username"` + LanguageCode string `json:"language_code"` + CanJoinGroups bool `json:"can_join_groups"` + CanReadAllGroupMessages bool `json:"can_read_all_group_messages"` + SupportsInlineQueries bool `json:"supports_inline_queries"` +} diff --git a/tg.go b/tg.go new file mode 100644 index 0000000..0dd6f70 --- /dev/null +++ b/tg.go @@ -0,0 +1,48 @@ +package tg + +import ( + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" +) + +func SendMessage(strBotSecret string, nChatID int64, strText string) { + // 5326579020:AAF4obMIPDujmzK73puieTcSBfk4JTlX1YI + + strURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%d&text=%s", + strBotSecret, nChatID, url.QueryEscape(strText), + ) + go Bytes(strURL) +} + +func SendMessageMarkdownV2(strBotSecret string, nChatID int64, strText string) { + // 5326579020:AAF4obMIPDujmzK73puieTcSBfk4JTlX1YI + + strURL := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%d&parse_mode=MarkdownV2&text=%s", + strBotSecret, nChatID, url.QueryEscape(strText), + ) + go Bytes(strURL) +} + +func Bytes(strURL string) ([]byte, error) { + resp, err := http.Get(strURL) + + if err != nil { + return nil, err + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + + return nil, err + } + + if resp.StatusCode != 200 { + return body, errors.New(resp.Status) + } + + return body, nil +}