qqbotapi

package module
v0.0.0-...-48d158a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 30, 2019 License: MIT Imports: 19 Imported by: 0

README

Golang bindings for the CoolQ HTTP API

GoDoc Build Status

This package is a golang SDK for CoolQ HTTP API. You can develop a QQ Bot that works based on CoolQ and CoolQ HTTP API plugin, with golang and this package.

The architectures and method names in this package are mainly inspired by go-telegram-bot-api. Meanwhile, we provide a couple of features like event emitter and chained api, inspired by other SDKs of CQHTTP. In most cases, this package gives you a friendly experience of developing bots in golang. You'll find it easy to navigate to this package, if you have once worked with go-telegram-bot-api or SDKs of CQHTTP in other languages. However, there are still use cases of CQHTTP that we do not cover with a good support ---- by design, for example, the scenario of using multiple CoolQ instance with one bot application.

Head through the following examples and godoc will give you a tutorial about how to use this package. If you still have problems, look up to the code or open an issue.

Communication Methods

CoolQ HTTP API provides several choices of communication method. The table below shows whether this SDK supports a kind of method.

Method API Event
HTTP √ *
WebHook (i.e. HTTP Reverse) √ **
WebSocket
WebSocket Reverse ×

* CQHTTP LongPolling Plugin is required to use this feature.
** Only limited operations (e.g. reply, approve) are provided by CQHTTP, in response to an event.

Quick Guide

This is a very simple bot that just displays any gotten updates, then replies it to that chat.

func main() {
	bot, err := qqbotapi.NewBotAPI("MyCoolqHttpToken", "http://localhost:5700", "CQHTTP_SECRET")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	u := qqbotapi.NewWebhook("/webhook_endpoint")
	u.PreloadUserInfo = true

	// Use WebHook as event method
	updates := bot.ListenForWebhook(u)
	// Or if you love WebSocket Reverse
	// updates := bot.ListenForWebSocket(u)
	go http.ListenAndServe("0.0.0.0:8443", nil)

	for update := range updates {
		if update.Message == nil {
			continue
		}

		log.Printf("[%s] %s", update.Message.From.String(), update.Message.Text)

		bot.SendMessage(update.Message.Chat.ID, update.Message.Chat.Type, update.Message.Text)
	}
}

If you need to utilize a sync response, it will be slightly different.

func main() {
	bot, err := qqbotapi.NewBotAPI("MyCoolqHttpToken", "http://localhost:5700", "CQHTTP_SECRET")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	u := qqbotapi.NewWebhook("/webhook_endpoint")
	u.PreloadUserInfo = true
	bot.ListenForWebhookSync(u, func(update qqbotapi.Update) interface{} {

		log.Printf("[%s] %s", update.Message.From.String(), update.Message.Text)

		return map[string]interface{}{
			"reply": update.Message.Text,
		}
	})

	http.ListenAndServe("0.0.0.0:8443", nil)
}

It's as easy as well if you prefer WebSocket or LongPolling as event method.

func main() {
	// Whether to use WebSocket or LongPolling depends on the address.
	// To use WebSocket, the address should be something like "ws://localhost:6700"
	bot, err := qqbotapi.NewBotAPI("MyCoolqHttpToken", "http://localhost:5700", "CQHTTP_SECRET")
	if err != nil {
		log.Fatal(err)
	}

	bot.Debug = true

	u := qqbotapi.NewUpdate(0)
	u.PreloadUserInfo = true
	updates, err := bot.GetUpdatesChan(u)
	
	for update := range updates {
		if update.Message == nil {
			continue
		}

		log.Printf("[%s] %s", update.Message.From.String(), update.Message.Text)

		bot.SendMessage(update.Message.Chat.ID, update.Message.Chat.Type, update.Message.Text)
	}
}

Event Emitter

If you come from Python/JavaScript, you'll be probably looking for this feature. We at here provide it as a helper that you may choose to use or not on your taste.

var bot *qqbotapi.BotAPI

func Log(update qqbotapi.Update) {
	log.Printf("[%s] %s", update.Message.From.String(), update.Message.Text)
}

func Echo(update qqbotapi.Update) {
	bot.SendMessage(update.Message.Chat.ID, update.Message.Chat.Type, update.Message.Text)
}

func main() {
	var err error
	bot, err = qqbotapi.NewBotAPI("MyCoolqHttpToken", "http://localhost:5700", "CQHTTP_SECRET")
	if err != nil {
		log.Fatal(err)
	}
	u := qqbotapi.NewWebhook("/webhook_endpoint")
	updates := bot.ListenForWebhook(u)
	go http.ListenAndServe("0.0.0.0:8443", nil)

	ev := qqbotapi.NewEv(updates)
	// Function Echo will get triggered on receiving an update with
	// PostType `message`, MessageType `group` and SubType `normal`
	ev.On("message.group.normal")(Echo)
	// Function Log will get triggered on receiving an update with
	// PostType `message`
	ev.On("message")(Log)

	// Keep main thread alive
	<-make(chan bool)
}

Messages

Update.Message.Message is a group of Media, defined in package cqcode.

	for update := range updates {
		if update.Message == nil {
			continue
		}

		for _, media := range *update.Message.Message {
			switch m := media.(type) {
			case *cqcode.Image:
				fmt.Printf(
					"The message includes an image, id: %s, url: %s",
					m.FileID,
					m.URL,
				)
			}
		}
	}

There are some useful command helpers.

	for update := range updates {
		if update.Message == nil {
			continue
		}

		// If this is true, a valid command must start with a command prefix (default to "/"),
		// false by default.
		cqcode.StrictCommand = true
		// Set command prefix
		cqcode.CommandPrefix = "/"

		if update.Message.IsCommand() {
			// cmd string, args []string
			// In a StrictCommand mode, the command prefix will be stripped off.
			cmd, args := update.Message.Command()

			// Note that cmd and args are still media
			cmdMedia, _ := cqcode.ParseMessage(cmd)
			for _, v := range cmdMedia {
				switch v.(type) {
				case *cqcode.At:
					fmt.Print("The command includes an At!")
				case *cqcode.Face:
					fmt.Print("The command includes a Face!")
				}
			}
		}
	}

Send Messages

The easiest way to send a message is to use a chained api.

	// Send a text-img message
	s := bot.NewMessage(10000000, "group").
		At("1232332333").
		Text("嘤嘤嘤").
		NewLine().
		FaceByName("调皮").
		Text("这是一个测试").
		ImageBase64("img.jpg").
		Send()

	// Withdraw that message
	if s.Err == nil {
		bot.DeleteMessage(s.Result.MessageID)
	}

	// Send a stand-alone message (No need to call Send())
	bot.NewMessage(10000000, "private").
		Dice()

You can also use bot.SendMessage.

	// All media types defined in package cqcode can be sent directly.
	// e.g. Send a text message
	bot.SendMessage(10000000, "group", cqcode.Text{
		Text: "[<- These will be encoded ->]",
	})

	// Send a location
	bot.SendMessage(10000000, "group", cqcode.Location{
		Content:   "上海市徐汇区交通大学华山路1954号",
		Latitude:  31.198878,
		Longitude: 121.436381,
		Style:     1,
		Title:     "位置分享",
	})

	// Send a message that contains a number of media.
	message := make(cqcode.Message, 0)
	message.Append(&cqcode.At{QQ: "all"})
	message.Append(&cqcode.Text{Text:" 大家起来嗨"})
	face, _ := cqcode.NewFaceFromName("调皮")
	message.Append(face)
	bot.SendMessage(10000000, "group", message)

	// To send an image or a record, you may use a helper function.
	// Format a base64-encoded image (Recommended)
	image1, err := qqbotapi.NewImageBase64("/path/to/image.jpg")

	// Format an image in the web.
	u, err := url.Parse("https://img.rikako.moe/i/D1D.jpg")
	image2 := qqbotapi.NewImageWeb(u)
	image2.DisableCache()

	// Format a local image if CQHTTP and your bot are under the same host.
	u, err = url.Parse("file:///tmp/D1D.jpg")
	image3 := qqbotapi.NewImageWeb(u)

Or you can manually use the function bot.Send and bot.Do with a "config". You should find this quite familiar if you have once developed a Telegram bot.

	// An alternative to bot.SendMessage and bot.DeleteMessage
	message := qqbotapi.NewMessage(10000000, "group", "aaaaaa")
	m, err := bot.Send(message)
	if err == nil {
		config := qqbotapi.DeleteMessageConfig{MessageID: m.MessageID}
		bot.Do(config)
	}

Documentation

Overview

Package qqbotapi has functions and types used for interacting with the Coolq HTTP API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewFileBase64

func NewFileBase64(file interface{}) (string, error)

NewFileBase64 formats a file into base64 format.

func NewFileLocal

func NewFileLocal(file string) string

NewFileLocal formats a file with the file path, returning the string.

This method is deprecated and will get removed, see #11. Please use NewFileWeb instead.

func NewImageBase64

func NewImageBase64(file interface{}) (*cqcode.Image, error)

NewImageBase64 formats an image in base64.

func NewImageLocal

func NewImageLocal(file string) *cqcode.Image

NewImageLocal formats an image with the file path, this requires CQ HTTP runs in the same host with your bot.

This method is deprecated and will get removed, see #11. Please use NewImageWeb instead.

func NewRecordBase64

func NewRecordBase64(file interface{}) (*cqcode.Record, error)

NewRecordBase64 formats a record in base64.

func NewRecordLocal

func NewRecordLocal(file string) *cqcode.Record

NewRecordLocal formats a record with the file path, this requires CQ HTTP runs in the same host with your bot.

This method is deprecated and will get removed, see #11. Please use NewRecordWeb instead.

Types

type APIResponse

type APIResponse struct {
	Status  string          `json:"status"`
	Data    json.RawMessage `json:"data"`
	RetCode int             `json:"retcode"`
	Echo    interface{}     `json:"echo"`
}

APIResponse is a response from the Coolq HTTP API with the result stored raw.

type BaseChat

type BaseChat struct {
	ChatID   int64 // required
	ChatType string
}

BaseChat is base type for all chat config types.

type BaseUpdateConfig

type BaseUpdateConfig struct {
	PreloadUserInfo bool // if this is enabled, more information will be provided in Update.From
}

BaseUpdateConfig contains information about loading updates.

type BotAPI

type BotAPI struct {
	Token       string `json:"token"`
	Secret      string `json:"secret"`
	Debug       bool   `json:"debug"`
	Buffer      int    `json:"buffer"`
	APIEndpoint string `json:"api_endpoint"`

	Self              User                     `json:"-"`
	Client            *http.Client             `json:"-"`
	WSAPIClient       *websocket.Conn          `json:"-"`
	WSEventClient     *websocket.Conn          `json:"-"`
	WSPendingRequests map[int]chan APIResponse `json:"-"`
	WSPendingMux      sync.Mutex               `json:"-"`
	WSRequestTimeout  time.Duration            `json:"-"`
	Echo              int                      `json:"-"`
	EchoMux           sync.Mutex               `json:"-"`
}

BotAPI allows you to interact with the Coolq HTTP API.

func NewBotAPI

func NewBotAPI(token string, api string, secret string) (*BotAPI, error)

NewBotAPI creates a new BotAPI instance.

token: access_token, api: API Endpoint of Coolq-http, example: http://host:port. secret: the secret key of HMAC SHA1 signature of Coolq-HTTP, won't be validated if left blank.

func NewBotAPIWithClient

func NewBotAPIWithClient(token string, api string, secret string) (*BotAPI, error)

NewBotAPIWithClient creates a new BotAPI instance

It requires a token, an API endpoint and a secret which you set in Coolq HTTP API.

func NewBotAPIWithWSClient

func NewBotAPIWithWSClient(token string, api string) (*BotAPI, error)

NewBotAPIWithWSClient creates a new BotAPI instance

It requires a token, an API endpoint which you set in Coolq HTTP API.

func (*BotAPI) DeleteMessage

func (bot *BotAPI) DeleteMessage(messageID int64) (APIResponse, error)

DeleteMessage deletes a message in a chat.

func (*BotAPI) Do

func (bot *BotAPI) Do(c Chattable) (APIResponse, error)

Do will send a Chattable item to Coolq.

It requires the Chattable to send.

func (*BotAPI) EnableAnonymousChat

func (bot *BotAPI) EnableAnonymousChat(groupID int64, enable bool) (APIResponse, error)

EnableAnonymousChat : By this enabled, members in a group will be able to send messages with an anonymous identity.

func (*BotAPI) GetGroupList

func (bot *BotAPI) GetGroupList() ([]Group, error)

GetGroupList fetches all groups

func (*BotAPI) GetGroupMemberInfo

func (bot *BotAPI) GetGroupMemberInfo(groupID int64, userID int64, noCache bool) (User, error)

GetGroupMemberInfo fetches a group member's user info.

Using cache may result in not updating in time, but will be responded faster

func (*BotAPI) GetGroupMemberList

func (bot *BotAPI) GetGroupMemberList(groupID int64) ([]User, error)

GetGroupMemberList fetches a group all member's user info.

This information might be not full or accurate enough.

func (*BotAPI) GetMe

func (bot *BotAPI) GetMe() (User, error)

GetMe fetches the currently authenticated bot.

This method is called upon creation to validate the token, and so you may get this data from BotAPI.Self without the need for another request.

func (*BotAPI) GetStrangerInfo

func (bot *BotAPI) GetStrangerInfo(userID int64) (User, error)

GetStrangerInfo fetches a stranger's user info.

func (*BotAPI) GetUpdates

func (bot *BotAPI) GetUpdates(config UpdateConfig) ([]Update, error)

GetUpdates fetches updates over long polling or websocket. https://github.com/richardchien/cqhttp-ext-long-polling

Offset, Limit, and Timeout are optional. To avoid stale items, set Offset to one higher than the previous item. Set Timeout to a large number to reduce requests so you can get updates instantly instead of having to wait between requests.

func (*BotAPI) GetUpdatesChan

func (bot *BotAPI) GetUpdatesChan(config UpdateConfig) (UpdatesChannel, error)

GetUpdatesChan starts and returns a channel that gets updates over long polling or websocket. https://github.com/richardchien/cqhttp-ext-long-polling

func (*BotAPI) HandleFriendRequest

func (bot *BotAPI) HandleFriendRequest(flag string, approve bool, remark string) (APIResponse, error)

HandleFriendRequest handles a friend request.

remark: 备注

func (*BotAPI) HandleGroupRequest

func (bot *BotAPI) HandleGroupRequest(flag string, typ string, approve bool, reason string) (APIResponse, error)

HandleGroupRequest handles a group adding request.

typ: sub_type in Update reason: Reason if you rejects this request.

func (*BotAPI) IsMessageToMe

func (bot *BotAPI) IsMessageToMe(message Message) bool

IsMessageToMe returns true if message directed to this bot.

It requires the Message.

func (*BotAPI) KickChatMember

func (bot *BotAPI) KickChatMember(groupID int64, userID int64, rejectAddRequest bool) (APIResponse, error)

KickChatMember kick a chat member in a group.

func (*BotAPI) LeaveChat

func (bot *BotAPI) LeaveChat(chatID int64, chatType string, dismiss bool) (APIResponse, error)

LeaveChat makes the bot leave the chat.

func (*BotAPI) Like

func (bot *BotAPI) Like(userID int64, times int) (APIResponse, error)

Like sends like (displayed in one's profile page) to a user.

func (*BotAPI) ListenForWebSocket

func (bot *BotAPI) ListenForWebSocket(config WebhookConfig) UpdatesChannel

ListenForWebSocket registers a http handler for a websocket and returns a channel that gets updates.

func (*BotAPI) ListenForWebhook

func (bot *BotAPI) ListenForWebhook(config WebhookConfig) UpdatesChannel

ListenForWebhook registers a http handler for a webhook and returns a channel that gets updates.

func (*BotAPI) ListenForWebhookSync

func (bot *BotAPI) ListenForWebhookSync(config WebhookConfig, handler func(update Update) interface{})

ListenForWebhookSync registers a http handler for a webhook.

handler receives a update and returns a key-value dictionary.

func (*BotAPI) MakeRequest

func (bot *BotAPI) MakeRequest(endpoint string, params url.Values) (APIResponse, error)

MakeRequest makes a request to a specific endpoint with our token.

func (*BotAPI) NewMessage

func (bot *BotAPI) NewMessage(chatID int64, chatType string) *Sender

NewMessage sends message to a chat.

func (*BotAPI) PreloadUserInfo

func (bot *BotAPI) PreloadUserInfo(update *Update)

PreloadUserInfo fills in the information in update.Message.From

func (*BotAPI) PromoteChatMember

func (bot *BotAPI) PromoteChatMember(groupID int64, userID int64, enable bool) (APIResponse, error)

PromoteChatMember add admin rights to user.

func (*BotAPI) RestrictAllChatMembers

func (bot *BotAPI) RestrictAllChatMembers(groupID int64, enable bool) (APIResponse, error)

RestrictAllChatMembers : By this enabled, only administrators in a group will be able to send messages.

func (*BotAPI) RestrictAnonymousChatMember

func (bot *BotAPI) RestrictAnonymousChatMember(groupID int64, flag string, duration time.Duration) (APIResponse, error)

RestrictAnonymousChatMember bans an anonymous chat member from sending messages.

func (*BotAPI) RestrictChatMember

func (bot *BotAPI) RestrictChatMember(groupID int64, userID int64, duration time.Duration) (APIResponse, error)

RestrictChatMember bans a chat member from sending messages.

func (*BotAPI) Send

func (bot *BotAPI) Send(c Chattable) (Message, error)

Send will send a Chattable item to Coolq. The response will be regarded as Message, often with a MessageID in it.

It requires the Chattable to send.

func (*BotAPI) SendMessage

func (bot *BotAPI) SendMessage(chatID int64, chatType string, message interface{}) (Message, error)

SendMessage sends message to a chat.

func (*BotAPI) SetChatMemberCard

func (bot *BotAPI) SetChatMemberCard(groupID int64, userID int64, card string) (APIResponse, error)

SetChatMemberCard sets a chat member's 群名片 in the group.

func (*BotAPI) SetChatMemberTitle

func (bot *BotAPI) SetChatMemberTitle(groupID int64, userID int64, title string, duration time.Duration) (APIResponse, error)

SetChatMemberTitle sets a chat member's 专属头衔 in the group.

type Chat

type Chat struct {
	ID      int64  `json:"id"`
	Type    string `json:"type"`     // "private"、"group"、"discuss"
	SubType string `json:"sub_type"` // (only when Type is "private") "friend"、"group"、"discuss"、"other"
}

Chat contains information about the place a message was sent.

func (Chat) IsDiscuss

func (c Chat) IsDiscuss() bool

IsDiscuss returns if the Chat is a discuss.

func (Chat) IsGroup

func (c Chat) IsGroup() bool

IsGroup returns if the Chat is a group.

func (Chat) IsPrivate

func (c Chat) IsPrivate() bool

IsPrivate returns if the Chat is a private conversation.

type ChatMemberConfig

type ChatMemberConfig struct {
	GroupID       int64
	UserID        int64
	AnonymousFlag string
}

ChatMemberConfig contains information about a user in a chat for use with administrative functions such as kicking or unbanning a user.

type Chattable

type Chattable interface {
	// contains filtered or unexported methods
}

Chattable is any config type that can be sent.

type DeleteMessageConfig

type DeleteMessageConfig struct {
	MessageID int64
}

DeleteMessageConfig contains information of a message in a chat to delete.

type EnableAnonymousChatConfig

type EnableAnonymousChatConfig struct {
	GroupControlConfig
}

EnableAnonymousChatConfig contains fields to enable anonymous chat.

type Ev

type Ev struct {
	// contains filtered or unexported fields
}

func NewEv

func NewEv(channel UpdatesChannel) *Ev

func (*Ev) Emit

func (ev *Ev) Emit(event string, update Update)

func (*Ev) Off

func (ev *Ev) Off(event string) func(func(update Update))

func (*Ev) On

func (ev *Ev) On(event string) func(func(update Update)) Unsubscribe

type File

type File struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Size  int64  `json:"size"`
	BusID int64  `json:"busid"`
}

File is a file.

type FlatSender

type FlatSender struct {
	ChatID   int64
	ChatType string

	Result *Message
	Err    error
	// contains filtered or unexported fields
}

func (*FlatSender) At

func (sender *FlatSender) At(QQ string) *FlatSender

func (*FlatSender) Emoji

func (sender *FlatSender) Emoji(emojiID int) *FlatSender

func (*FlatSender) Face

func (sender *FlatSender) Face(faceID int) *FlatSender

func (*FlatSender) FaceByName

func (sender *FlatSender) FaceByName(faceName string) *FlatSender

func (*FlatSender) ImageBase64

func (sender *FlatSender) ImageBase64(file interface{}) *FlatSender

func (*FlatSender) ImageLocal

func (sender *FlatSender) ImageLocal(file string) *FlatSender

This method is deprecated and will get removed, see #11. Please use ImageWeb instead.

func (*FlatSender) ImageWeb

func (sender *FlatSender) ImageWeb(url *url.URL) *FlatSender

func (*FlatSender) NewLine

func (sender *FlatSender) NewLine() *FlatSender

func (*FlatSender) Send

func (sender *FlatSender) Send() *Sender

func (*FlatSender) Sface

func (sender *FlatSender) Sface(sfaceID int) *FlatSender

func (*FlatSender) Text

func (sender *FlatSender) Text(text string) *FlatSender

type Group

type Group struct {
	ID   int64  `json:"group_id"`
	Name string `json:"group_name"`
}

Group is a group on QQ.

type GroupControlConfig

type GroupControlConfig struct {
	GroupID int64
	Enable  bool
}

GroupControlConfig contains fields as a configuration of a group.

type HandleFriendRequestConfig

type HandleFriendRequestConfig struct {
	HandleRequestConfig
	Remark string
}

HandleFriendRequestConfig contains fields to handle a friend request.

type HandleGroupRequestConfig

type HandleGroupRequestConfig struct {
	HandleRequestConfig
	Type   string
	Reason string
}

HandleGroupRequestConfig contains fields to handle a group adding request.

type HandleRequestConfig

type HandleRequestConfig struct {
	RequestFlag string
	Approve     bool
}

HandleRequestConfig contains fields to handle a request.

type KickChatMemberConfig

type KickChatMemberConfig struct {
	ChatMemberConfig
	RejectAddRequest bool
}

KickChatMemberConfig contains extra fields to kick user.

type LeaveChatConfig

type LeaveChatConfig struct {
	BaseChat
	IsDismiss bool
}

LeaveChatConfig contains fields to leave a chat.

type LikeConfig

type LikeConfig struct {
	UserID int64
	Times  int
}

LikeConfig contains information of a like (displayed on personal profile page) to send.

type Message

type Message struct {
	*cqcode.Message `json:"message"`
	MessageID       int64  `json:"message_id"`
	From            *User  `json:"from"`
	Chat            *Chat  `json:"chat"`
	Text            string `json:"text"`
	SubType         string `json:"sub_type"` // (only when Chat.Type is "group") "normal"、"anonymous"、"notice"
	Font            int    `json:"font"`
}

Message is returned by almost every request, and contains data about almost anything.

func (Message) IsAnonymous

func (m Message) IsAnonymous() bool

IsAnonymous returns if a message is an anonymous message.

func (Message) IsNotice

func (m Message) IsNotice() bool

IsNotice returns if a message is a notice.

type MessageConfig

type MessageConfig struct {
	BaseChat
	Text       string
	AutoEscape bool
}

MessageConfig contains information about a SendMessage request.

func NewMessage

func NewMessage(chatID int64, chatType string, message interface{}) MessageConfig

NewMessage creates a new Message.

chatID is where to send it, message is the message.

type NetImage

type NetImage struct {
	*cqcode.Image
	*NetResource
}

NetImage is an image located in the Internet.

func NewImageWeb

func NewImageWeb(url *url.URL) *NetImage

NewImageWeb formats an image with the URL.

type NetRecord

type NetRecord struct {
	*cqcode.Record
	*NetResource
}

NetRecord is a record located in the Internet.

func NewRecordWeb

func NewRecordWeb(url *url.URL) *NetRecord

NewRecordWeb formats a record with the URL.

type NetResource

type NetResource struct {
	Cache int `cq:"cache"`
}

NetResource is a resource located in the Internet.

func (*NetResource) DisableCache

func (r *NetResource) DisableCache()

DisableCache forces CQ HTTP download from the URL instead of using cache.

func (*NetResource) EnableCache

func (r *NetResource) EnableCache()

EnableCache enables CQ HTTP's cache feature.

type PromoteChatMemberConfig

type PromoteChatMemberConfig struct {
	ChatMemberConfig
	Enable bool
}

PromoteChatMemberConfig contains fields to promote members of chat.

type RestrictAllChatMembersConfig

type RestrictAllChatMembersConfig struct {
	GroupControlConfig
}

RestrictAllChatMembersConfig contains fields to restrict all chat members.

type RestrictChatMemberConfig

type RestrictChatMemberConfig struct {
	ChatMemberConfig
	Duration time.Duration
}

RestrictChatMemberConfig contains fields to restrict members of chat.

type Sender

type Sender struct {
	*FlatSender
}

func NewSender

func NewSender(bot *BotAPI, chatID int64, chatType string) *Sender

func (*Sender) Bface

func (sender *Sender) Bface(bfaceID int) *Sender

func (*Sender) Dice

func (sender *Sender) Dice() *Sender

func (*Sender) Location

func (sender *Sender) Location(loc cqcode.Location) *Sender

func (*Sender) Music

func (sender *Sender) Music(music cqcode.Music) *Sender

func (*Sender) RecordBase64

func (sender *Sender) RecordBase64(file interface{}, magic bool) *Sender

func (*Sender) RecordLocal

func (sender *Sender) RecordLocal(file string, magic bool) *Sender

This method is deprecated and will get removed, see #11. Please use RecordWeb instead.

func (*Sender) RecordWeb

func (sender *Sender) RecordWeb(url *url.URL, magic bool) *Sender

func (*Sender) Rps

func (sender *Sender) Rps() *Sender

func (*Sender) Shake

func (sender *Sender) Shake(emojiID int) *Sender

func (*Sender) Share

func (sender *Sender) Share(share cqcode.Share) *Sender

func (*Sender) Show

func (sender *Sender) Show(id int) *Sender

func (*Sender) Sign

func (sender *Sender) Sign(sign cqcode.Sign) *Sender

type SetChatMemberCardConfig

type SetChatMemberCardConfig struct {
	ChatMemberConfig
	Card string
}

SetChatMemberCardConfig contains fields to set members's 群名片.

type SetChatMemberTitleConfig

type SetChatMemberTitleConfig struct {
	ChatMemberConfig
	SpecialTitle string
	Duration     time.Duration
}

SetChatMemberTitleConfig contains fields to set members's 专属头衔.

type Unsubscribe

type Unsubscribe func()

type Update

type Update struct {
	Time          int64       `json:"time"`
	PostType      string      `json:"post_type"`
	MessageType   string      `json:"message_type"`
	SubType       string      `json:"sub_type"`
	MessageID     int64       `json:"message_id"`
	GroupID       int64       `json:"group_id"`
	DiscussID     int64       `json:"discuss_id"`
	UserID        int64       `json:"user_id"`
	Font          int         `json:"font"`
	RawMessage    interface{} `json:"message"`        // Could be string or array, depends on configuration of coolq-http-api
	Anonymous     interface{} `json:"anonymous"`      // This field type is for backward-compatibility and might get changed, see #11
	AnonymousFlag string      `json:"anonymous_flag"` // This field is deprecated and will get removed, see #11
	Event         string      `json:"event"`
	NoticeType    string      `json:"notice_type"` // This field is deprecated and will get removed, see #11
	OperatorID    int64       `json:"operator_id"`
	File          *File       `json:"file"`
	RequestType   string      `json:"request_type"`
	Flag          string      `json:"flag"`
	Comment       string      `json:"comment"` // This field is used for Request Event
	Text          string      `json:"-"`       // Message with CQCode
	Message       *Message    `json:"-"`       // Message parsed
	Sender        *User       `json:"sender"`
}

Update is an update response, from GetUpdates.

func (*Update) ParseRawMessage

func (update *Update) ParseRawMessage()

ParseRawMessage parses message

type UpdateConfig

type UpdateConfig struct {
	BaseUpdateConfig
	Offset  int
	Limit   int
	Timeout int
}

UpdateConfig contains information about a GetUpdates request.

func NewUpdate

func NewUpdate(offset int) UpdateConfig

NewUpdate gets updates since the last Offset.

offset is the last Update ID to include. You likely want to set this to the last Update ID plus 1.

type UpdatesChannel

type UpdatesChannel <-chan Update

UpdatesChannel is the channel for getting updates.

type User

type User struct {
	ID       int64  `json:"user_id"`
	NickName string `json:"nickname"`
	Sex      string `json:"sex"` // "male"、"female"、"unknown"
	Age      int    `json:"age"`
	Area     string `json:"area"`
	// Group member
	Card                string `json:"card"`
	CardChangeable      bool   `json:"card_changeable"`
	Title               string `json:"title"`
	TitleExpireTimeUnix int64  `json:"title_expire_time"`
	Level               string `json:"level"`
	Role                string `json:"role"` // "owner"、"admin"、"member"
	Unfriendly          bool   `json:"unfriendly"`
	JoinTimeUnix        int64  `json:"join_time"`
	LastSentTimeUnix    int64  `json:"last_sent_time"`
	AnonymousID         int64  `json:"anonymous_id" anonymous:"id"`
	AnonymousName       string `json:"anonymous_name" anonymous:"name"`
	AnonymousFlag       string `json:"anonymous_flag" anonymous:"flag"`
}

User is a user on QQ.

func (*User) Name

func (u *User) Name() string

Name displays a simple text version of a user.

func (*User) String

func (u *User) String() string

String displays a simple text version of a user.

It is normally a user's card, but falls back to a nickname as available.

type WebSocketRequest

type WebSocketRequest struct {
	Action string                 `json:"action"`
	Params map[string]interface{} `json:"params"`
	Echo   interface{}            `json:"echo"`
}

type WebhookConfig

type WebhookConfig struct {
	BaseUpdateConfig
	Pattern string // the webhook endpoint
}

WebhookConfig contains information about a webhook.

func NewWebhook

func NewWebhook(pattern string) WebhookConfig

NewWebhook registers a webhook.

Directories

Path Synopsis
Package cqcode provides basic structs of cqcode media, and utilities of parsing and formatting cqcode
Package cqcode provides basic structs of cqcode media, and utilities of parsing and formatting cqcode

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL