Documentation
¶
Index ¶
- Constants
- Variables
- func ComputeFlagChanges(oldFlags, newFlags int64) (addedFlags, removedFlags int64)
- func Contains[T comparable](arr []T, item T) bool
- func CopyMap[K comparable, V any](src, dst map[K]V)
- func CreateAnonSeed(name, sid string) (seed string)
- func FileExists(filename string) bool
- func FindClosestMatch(source []string, target string) (match string, ratio float64)
- func GenerateRandomString(length int) string
- func GetAnonName(seed, sid string) (name string)
- func GetServer(name string) string
- func IsDigit(strnum string) bool
- func Max[T Number](a T, b ...T) (c T)
- func Min[T Number](a T, b ...T) (c T)
- func ParseTime(strtime string) (t time.Time, err error)
- func Remove[T comparable](arr []T, item T) []T
- func SaveConfig(filename string, config *Config) error
- func SplitTextIntoChunks(text string, chunkSize int) (chunks []string)
- type API
- func (api *API) GetBackgroundInfo(username string) (info BackgroundInfo, err error)
- func (api *API) GetCookie(cookiename string) (cookie string, ok bool)
- func (api *API) GetFullProfile(username string) (profile FullProfile, err error)
- func (api *API) GetGroupList() (groups MyChatGroups, err error)
- func (api *API) GetMiniProfile(username string) (profile MiniProfile, err error)
- func (api *API) GetToken(gcmID string) (token string, err error)
- func (api *API) Initialize() (err error)
- func (api *API) IsGroup(groupname string) (answer bool, err error)
- func (api *API) RegisterGCM(gcmID, token string) (err error)
- func (api *API) SearchPeople(query PeopleQuery) (usernames [][2]string, err error)
- func (api *API) UnregisterGCM(gcmID string) (err error)
- type Application
- func (app *Application) AddHandler(handler Handler) *Application
- func (app *Application) ConnectPM() error
- func (app *Application) DisconnectPM()
- func (app *Application) Dispatch(event *Event)
- func (app *Application) Initialize()
- func (app *Application) JoinGroup(groupName string) error
- func (app *Application) LeaveGroup(groupName string) error
- func (app *Application) Park()
- func (app *Application) RemoveHandler(handler Handler)
- func (app *Application) Start(ctx context.Context)
- func (app *Application) Stop()
- type BackgroundInfo
- type Backoff
- type BanWord
- type BirthDate
- type Blocked
- type Callback
- type ChatFilter
- func (f *ChatFilter) Add(chatName string)
- func (f *ChatFilter) And(filter Filter) Filter
- func (f *ChatFilter) Check(event *Event) bool
- func (f *ChatFilter) Not() Filter
- func (f *ChatFilter) Or(filter Filter) Filter
- func (f *ChatFilter) Remove(chatName string)
- func (f *ChatFilter) Xor(filter Filter) Filter
- type CombineFilter
- type CommandHandler
- type Config
- type Context
- type Event
- type EventType
- type Filter
- type FullProfile
- type Group
- func (g *Group) AddModerator(username string, access int64) (err error)
- func (g *Group) BanUser(message *Message) (err error)
- func (g *Group) ClearAll() (err error)
- func (g *Group) Connect(ctx context.Context) (err error)
- func (g *Group) Delete(message *Message) (err error)
- func (g *Group) DeleteAll(message *Message) (err error)
- func (g *Group) Disconnect()
- func (g *Group) GetAnnouncement() (annc string, enabled bool, interval time.Duration, err error)
- func (g *Group) GetBanList(offset time.Time, ammount int) (banList []Blocked, err error)
- func (g *Group) GetBanWords() (banWord BanWord, err error)
- func (g *Group) GetContext() context.Context
- func (g *Group) GetLastUserMessage(username string) (msg *Message, ok bool)
- func (g *Group) GetModActions(dir string, offset int) (modactions []*ModAction, err error)
- func (g *Group) GetParticipantsStart() (p *SyncMap[string, *Participant], err error)
- func (g *Group) GetParticipantsStop() error
- func (g *Group) GetPremiumInfo() (flag int, expire time.Time, err error)
- func (g *Group) GetRateLimit() (rate, current time.Duration, err error)
- func (g *Group) GetUnbanList(offset time.Time, ammount int) (unbanList []Unblocked, err error)
- func (g *Group) IsRestricted() bool
- func (g *Group) Login(username, password string) (err error)
- func (g *Group) Logout() (err error)
- func (g *Group) ProfileRefresh() error
- func (g *Group) PropagateEvent(frame string)
- func (g *Group) Reconnect() (err error)
- func (g *Group) RemoveModerator(username string) (err error)
- func (g *Group) SearchBannedUser(query string) (banned Blocked, ok bool)
- func (g *Group) Send(args ...string) error
- func (g *Group) SendMessage(text string) (msg *Message, err error)
- func (g *Group) SendMessageChunked(text string, chunkSize int) (msgs []*Message, err error)
- func (g *Group) SetAnnouncement(annc string, enable bool, interval time.Duration) (err error)
- func (g *Group) SetBackground(enable bool) (err error)
- func (g *Group) SetBanWords(banWord BanWord) (err error)
- func (g *Group) SetMedia(enable bool) (err error)
- func (g *Group) SetRateLimit(interval time.Duration) (rate time.Duration, err error)
- func (g *Group) SyncSend(cb func(string) bool, text ...string) error
- func (g *Group) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
- func (g *Group) UnbanAll() (err error)
- func (g *Group) UnbanUser(blocked *Blocked) (err error)
- func (g *Group) UpdateGroupFlag(addition, removal int64) (err error)
- func (g *Group) UpdateModerator(username string, access int64) (err error)
- type GroupInfo
- type Handler
- type KeyValue
- type Location
- type Message
- func (m *Message) BanUser() error
- func (m *Message) Channel() int64
- func (m *Message) Delete() error
- func (m *Message) DeleteAll() error
- func (m *Message) HasBackground() bool
- func (m *Message) HasMedia() bool
- func (m *Message) HasPremium() bool
- func (m *Message) NameColor() string
- func (m *Message) Reply(text string) (*Message, error)
- func (m *Message) TextStyle() (textColor, textFont string, textSize int)
- type MessageHandler
- type MiniProfile
- type ModAction
- func (ma *ModAction) ExtraAsBool() (ret bool)
- func (ma *ModAction) ExtraAsInt() (ret int64)
- func (ma *ModAction) ExtraAsSliceInt() (ret []int64)
- func (ma *ModAction) ExtraAsSliceInterface() (ret []interface{})
- func (ma *ModAction) ExtraBanWord() (ret BanWord)
- func (ma *ModAction) ExtraDescription() (ret GroupInfo)
- func (ma *ModAction) String() (actionDesc string)
- type MyChatGroups
- type NotFilter
- type Number
- type OrderedSyncMap
- func (sm *OrderedSyncMap[K, V]) Clear()
- func (sm *OrderedSyncMap[K, V]) Del(key K)
- func (sm *OrderedSyncMap[K, V]) Get(key K) (val V, ok bool)
- func (sm *OrderedSyncMap[K, V]) GobDecode(data []byte) error
- func (sm *OrderedSyncMap[K, V]) GobEncode() ([]byte, error)
- func (sm *OrderedSyncMap[K, V]) Keys() []K
- func (sm *OrderedSyncMap[K, V]) Len() int
- func (sm *OrderedSyncMap[K, V]) Range(fun func(K, V) bool)
- func (sm *OrderedSyncMap[K, V]) RangeReversed(fun func(K, V) bool)
- func (sm *OrderedSyncMap[K, V]) Set(key K, val V)
- func (sm *OrderedSyncMap[K, V]) SetFront(key K, val V)
- func (sm *OrderedSyncMap[K, V]) TrimFront(length int)
- type Participant
- type PeopleQuery
- type Persistence
- func (p *Persistence) Close() error
- func (p *Persistence) DelChatData(key string)
- func (p *Persistence) GetBotData() *SyncMap[string, any]
- func (p *Persistence) GetChatData(key string) *SyncMap[string, any]
- func (p *Persistence) Initialize() error
- func (p *Persistence) Load() error
- func (p *Persistence) Save() error
- type PremiumDate
- type Private
- func (p *Private) AddFriend(username string) (status UserStatus, err error)
- func (p *Private) Block(username string) (err error)
- func (p *Private) Connect(ctx context.Context) (err error)
- func (p *Private) ConnectUser(username string) (status UserStatus, err error)
- func (p *Private) Disconnect()
- func (p *Private) DisconnectUser(username string) (err error)
- func (p *Private) GetBlocked() (users []*User, err error)
- func (p *Private) GetContext() context.Context
- func (p *Private) GetFriendList() (friendlist []UserStatus, err error)
- func (p *Private) GetPresence(usernames []string) (statuslist []UserStatus, err error)
- func (p *Private) GetSettings() (setting PrivateSetting, err error)
- func (p *Private) ProfileRefresh() error
- func (p *Private) PropagateEvent(frame string)
- func (p *Private) Reconnect() (err error)
- func (p *Private) RemoveFriend(username string) (err error)
- func (p *Private) Send(args ...string) error
- func (p *Private) SendMessage(username, text string) (err error)
- func (p *Private) SetSettings(setting PrivateSetting) (err error)
- func (p *Private) SyncSend(cb func(string) bool, text ...string) error
- func (p *Private) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
- func (p *Private) Track(username string) (status UserStatus, err error)
- func (p *Private) Unblock(username string) (err error)
- func (p *Private) WentActive()
- func (p *Private) WentIdle()
- type PrivateSetting
- type QueryEscaped
- type RegexFilter
- type SyncMap
- func (sm *SyncMap[K, V]) Clear()
- func (sm *SyncMap[K, V]) Del(key K)
- func (sm *SyncMap[K, V]) Get(key K) (val V, ok bool)
- func (sm *SyncMap[K, V]) GobDecode(data []byte) error
- func (sm *SyncMap[K, V]) GobEncode() ([]byte, error)
- func (sm *SyncMap[K, V]) Keys() (keys []K)
- func (sm *SyncMap[K, V]) Len() int
- func (sm *SyncMap[K, V]) Range(fun func(K, V) bool)
- func (sm *SyncMap[K, V]) Set(key K, val V)
- type Transport
- type TypeHandler
- type Unblocked
- type User
- type UserFilter
- func (f *UserFilter) Add(userName string)
- func (f *UserFilter) And(filter Filter) Filter
- func (f *UserFilter) Check(event *Event) bool
- func (f *UserFilter) Not() Filter
- func (f *UserFilter) Or(filter Filter) Filter
- func (f *UserFilter) Remove(userName string)
- func (f *UserFilter) Xor(filter Filter) Filter
- type UserStatus
- type WebSocket
Constants ¶
const ( WEBSOCKET_ORIGIN = "http://st.chatango.com" PM_SERVER = "ws://c1.chatango.com:8080/" EVENT_BUFFER_SIZE = 30 PING_INTERVAL = 90 * time.Second DEFAULT_COLOR = "000" DEFAULT_TEXT_FONT = "1" DEFAULT_TEXT_SIZE = 11 MAX_MESSAGE_HISTORY = 100 SYNC_SEND_TIMEOUT = 5 * time.Second BASE_BACKOFF_DUR = 1 * time.Second MAX_BACKOFF_DUR = 30 * time.Second MAX_RETRIES = 10 MSG_LENGTH_DEFAULT = 2900 MSG_LENGTH_SHORT = 850 API_TIMEOUT = 10 * time.Second BOT_DATA_KEY = "<BOTDATA>" )
const ( FlagPremium int64 FlagBackground FlagMedia FlagModIcon FlagStaffIcon FlagRedChannel FlagBlueChannel FlagModChannel )
const ( EndFrame = "STOP" Charset = "abcdefghijklmnopqrstuvwxyz0123456789" )
const ( // CombineFilterAnd combines filter using logical AND. CombineFilterAnd int = iota // CombineFilterAnd combines filter using logical OR. CombineFilterOr // CombineFilterAnd combines filter using logical XOR. CombineFilterXor )
Variables ¶
var ( ErrNotAGroup = errors.New("not a group") ErrNotConnected = errors.New("not connected") ErrAlreadyConnected = errors.New("already connected") ErrConnectionClosed = errors.New("connection closed") ErrRetryEnds = errors.New("connection closed") ErrLoginFailed = errors.New("failed to login") ErrInvalidResponse = errors.New("invalid response") ErrNoArgument = errors.New("no argument") ErrTimeout = errors.New("timeout") ErrRateLimited = errors.New("rate limited") ErrCLimited = errors.New("climited") ErrMessageLength = errors.New("message length exceeded") ErrFloodWarning = errors.New("flood warning") ErrFloodBanned = errors.New("flood banned") ErrNonSenseWarning = errors.New("nonsense warning") ErrSpamWarning = errors.New("spam warning") ErrShortWarning = errors.New("short warning") ErrRestricted = errors.New("restricted") ErrMustLogin = errors.New("must login") ErrProxyBanned = errors.New("proxy banned") ErrVerificationRequired = errors.New("verification required") ErrUpdateFailed = errors.New("update failed") ErrClearFailed = errors.New("clear failed") ErrAddModFailed = errors.New("clear failed") ErrUpdateModFailed = errors.New("clear failed") ErrRemoveModFailed = errors.New("clear failed") ErrBadAlias = errors.New("bad alias") ErrBadLogin = errors.New("bad login") ErrPremiumExpired = errors.New("premium expired") ErrInvalidUsername = errors.New("invalid username") ErrInvalidArgument = errors.New("invalid argument") ErrOfflineLimit = errors.New("offline message limit") ErrSetTokenFailed = errors.New("settoken failed") ErrGCMRegFailed = errors.New("GCM register failed") ErrGCMUnregFailed = errors.New("GCM unregister failed") )
var ( AnonSeedRe = regexp.MustCompile(`<n\d{4}/>`) NameColorRe = regexp.MustCompile(`<n([\da-fA-F]{1,6})\/>`) FontStyleRe = regexp.MustCompile(`<f x([\da-fA-F]+)?="([\d\w]+)?">`) PrivateFontStyleRe = regexp.MustCompile(`<g x(\d+)?s([\da-fA-F]+)?="([\d\w]+)?">`) HtmlTagRe = regexp.MustCompile(`<.*?>`) NameFontTag = regexp.MustCompile(`<[nf][^>]*>`) )
var GroupPermissions = map[string]int64{
"DELETED": 1,
"EDIT_MODS": 2,
"EDIT_MOD_VISIBILITY": 4,
"EDIT_BW": 8,
"EDIT_RESTRICTIONS": 16,
"EDIT_GROUP": 32,
"SEE_COUNTER": 64,
"SEE_MOD_CHANNEL": 128,
"SEE_MOD_ACTIONS": 256,
"EDIT_NLP": 512,
"EDIT_GP_ANNC": 1024,
"EDIT_ADMINS": 2048,
"EDIT_SUPERMODS": 4096,
"NO_SENDING_LIMITATIONS": 8192,
"SEE_IPS": 16384,
"CLOSE_GROUP": 32768,
"CAN_BROADCAST": 65536,
"MOD_ICON_VISIBLE": 131072,
"IS_STAFF": 262144,
"STAFF_ICON_VISIBLE": 524288,
"UNBAN_ALL": 1048576,
}
var GroupStatuses = map[string]int64{
"MISSING_1": 1,
"NO_ANONS": 4,
"MISSING_2": 8,
"NO_COUNTER": 16,
"DISALLOW_IMAGES": 32,
"DISALLOW_LINKS": 64,
"DISALLOW_VIDEOS": 128,
"MISSING_3": 256,
"MISSING_4": 512,
"BANWORD_ONLY_TO_AUTHOR": 1024,
"FLOOD_CONTROLLED": 2048,
"ENABLE_CHANNELS": 8192,
"BASIC_NONSENSE_DETECTION": 16384,
"BLOCK_REPETITIOUS_MSGS": 32768,
"BROADCAST_MODE": 65536,
"CLOSED_NO_MODS": 131072,
"GROUP_CLOSED": 262144,
"DISPLAY_BADGES": 524288,
"MODS_CHOOSE_BADGES": 1048576,
"ADV_NONSENSE_DETECTION": 2097152,
"BAN_PROXIES_AND_VPN": 4194304,
"MISSING_5": 8388608,
"MISSING_6": 268435456,
"MISSING_7": 536870912,
}
var ModactionTmpl = map[string]string{
"mod_actions_title": "Moderator Actions Log",
"mod_actions_title_sm": "Moderator Log",
"action_desc_amod": "*name**ip* made *target* a moderator",
"action_desc_aadm": "*name**ip* made *target* an administrator",
"action_desc_rmod": "*name**ip* removed *target* as a moderator",
"action_desc_radm": "*name**ip* removed *target* as an administrator",
"action_desc_emod": "*name**ip*",
"added_perm": "gave *target* permission to: *added*",
"and": "and",
"removed_perm": "removed *target*'s permission to: *removed*",
"action_desc_chrl": "*name**ip* changed rate limit to *rl*",
"action_desc_anon": "*name**ip* *didallow* anons in the group",
"action_desc_prxy": "*name**ip* *didallow* messaging from proxies and VPNs in the group",
"action_desc_brdc": "*name**ip* *didenable* broadcast mode",
"action_desc_cinm": "*name**ip* *didenable* closed without moderators mode",
"action_desc_acls": "Group auto-closed since no moderators were online",
"action_desc_aopn": "Group re-opened upon moderator login",
"action_desc_chan": "*name**ip* *didenable* channels in the group",
"action_desc_cntr": "*name**ip* *didenable* the counter in the group",
"action_desc_chbw": "*name**ip* changed banned words",
"action_desc_enlp": "*name**ip* changed auto-moderation to",
"action_desc_annc": "*name**ip* *didenable* auto-announcement",
"action_desc_egrp": "*name**ip* edited group",
"action_desc_shwi": "*name**ip* forced moderators to show a badge",
"action_desc_hidi": "*name**ip* hid all moderator badges",
"action_desc_chsi": "*name**ip* let moderators choose their own badge visibility",
"action_desc_ubna": "*name**ip* removed all bans",
"enable_annc": "every *n* seconds: *msg*",
"perm_edit_mods": "add, remove and edit mods",
"perm_edit_mod_visibility": "edit mod visibility",
"perm_edit_bw": "edit banned content",
"perm_edit_restrictions": "edit chat restrictions",
"perm_edit_group": "edit group",
"perm_see_counter": "see counter",
"perm_see_mod_channel": "see mod channel",
"perm_see_mod_actions": "see mod actions log",
"perm_can_broadcast": "send messages in broadcast mode",
"perm_edit_nlp": "edit auto-moderation",
"perm_edit_gp_annc": "edit group announcement",
"perm_no_sending_limitations": "bypass message sending limitations",
"perm_see_ips": "see IPs",
"perm_is_staff": "display staff badge",
"perm_close_group": "close group input",
"perm_unban_all": "unban all",
"flood_cont": "flood controlled",
"slow_mode": "slow mode restricted to *time* *secs*",
"second": "second",
"seconds": "seconds",
"disallowed": "disallowed",
"allowed": "allowed",
"enabled": "enabled",
"disabled": "disabled",
"nlp_single_msg": "nonsense messages (basic)",
"nlp_msg_queue": "repetitious messages",
"nlp_ngram": "nonsense messages (advanced)",
"allow": "allow",
"block": "block",
}
Functions ¶
func ComputeFlagChanges ¶
ComputeFlagChanges computes the flag changes between the oldFlags and newFlags values.
func Contains ¶
func Contains[T comparable](arr []T, item T) bool
Contains is a generic function that checks whether the specified item is present in the given array.
func CopyMap ¶
func CopyMap[K comparable, V any](src, dst map[K]V)
CopyMap is a generic function that copies the source map to the destination map.
func CreateAnonSeed ¶
CreateAnonSeed creates an anonymous seed using the provided name and sid.
func FileExists ¶
FileExists checks whether the specified file exists.
func FindClosestMatch ¶
FindClosestMatch finds the closest matching string in the source array for the target string.
func GenerateRandomString ¶
GenerateRandomString generates a random string of the specified length.
func GetAnonName ¶
GetAnonName generates an anonymous name using the provided seed and sid.
func GetServer ¶
GetServer retrieves the server URL for the specified name. This function takes a string as input and returns a URL string for a server based on the input string. The returned URL is used for establishing a WebSocket connection. The function uses a weighted round-robin algorithm to select a server based on the input string. The input string is first converted to base36 integer by replacing "_" and "-" characters with "q". The first and second halves of the modified string are used to calculate a modulus ratio. The modulus ratio is then used to select a server based on its weight. The function returns a default URL if no server is selected.
func Max ¶
func Max[T Number](a T, b ...T) (c T)
Max is a generic function that returns the maximum value among the provided numbers.
func Min ¶
func Min[T Number](a T, b ...T) (c T)
Min is a generic function that returns the minimum value among the provided numbers.
func ParseTime ¶
ParseTime parses the provided string representation of time into a time.Time value.
func Remove ¶
func Remove[T comparable](arr []T, item T) []T
Remove is a generic function that removes the specified item from the given array.
func SaveConfig ¶
SaveConfig saves the configuration to the specified file.
func SplitTextIntoChunks ¶
SplitTextIntoChunks splits the provided text into chunks of the specified size.
Types ¶
type API ¶
API is a struct representing a compilation of various Chatango APIs.
func (*API) GetBackgroundInfo ¶
func (api *API) GetBackgroundInfo(username string) (info BackgroundInfo, err error)
GetBackgroundInfo retrieves the background information of the specified username.
func (*API) GetFullProfile ¶
func (api *API) GetFullProfile(username string) (profile FullProfile, err error)
GetFullProfile retrieves the full profile of the specified username.
func (*API) GetGroupList ¶
func (api *API) GetGroupList() (groups MyChatGroups, err error)
GetGroupList retrieves the user's chat group list.
func (*API) GetMiniProfile ¶
func (api *API) GetMiniProfile(username string) (profile MiniProfile, err error)
GetMiniProfile retrieves the mini profile of the specified username.
func (*API) Initialize ¶
Initialize initializes the Chatango API client and retrieves cookies from the specified username and password. It authenticates the client by obtaining and storing the necessary cookies. The retrieved cookies will be stored in the API's cookies field for external access through `api.GetCookie`.
func (*API) RegisterGCM ¶
RegisterGCM registers the specified GCM ID with the provided token.
func (*API) SearchPeople ¶
func (api *API) SearchPeople(query PeopleQuery) (usernames [][2]string, err error)
SearchPeople searches for people based on the provided query. It returns a list of usernames and online status data.
func (*API) UnregisterGCM ¶
UnregisterGCM unregisters the specified GCM ID.
type Application ¶
type Application struct { Config *Config // Config holds the configuration for the application. Persistence *Persistence // Persistence manages data persistence for the application. API *API // API provides access to various Chatango APIs used by the application. Private Private // Private represents the private chat functionality of the application. Groups SyncMap[string, *Group] // Groups stores the groups the application is connected to. // contains filtered or unexported fields }
Application represents the main application.
func New ¶
func New(config *Config) *Application
func (*Application) AddHandler ¶
func (app *Application) AddHandler(handler Handler) *Application
AddHandler adds a new handler to the application. It returns the `*Application` to allow for nesting.
func (*Application) ConnectPM ¶
func (app *Application) ConnectPM() error
ConnectPM connects to private messages.
func (*Application) DisconnectPM ¶
func (app *Application) DisconnectPM()
DisconnectPM disconnects from private messages.
func (*Application) Dispatch ¶
func (app *Application) Dispatch(event *Event)
Dispatch dispatches an event to the appropriate handler.
func (*Application) Initialize ¶
func (app *Application) Initialize()
Initialize initializes the application.
func (*Application) JoinGroup ¶
func (app *Application) JoinGroup(groupName string) error
JoinGroup joins a group in the application.
func (*Application) LeaveGroup ¶
func (app *Application) LeaveGroup(groupName string) error
LeaveGroup leaves a group in the application.
func (*Application) Park ¶
func (app *Application) Park()
Park waits for the application to stop or receive an interrupt signal.
func (*Application) RemoveHandler ¶
func (app *Application) RemoveHandler(handler Handler)
RemoveHandler removes a handler from the application.
func (*Application) Start ¶
func (app *Application) Start(ctx context.Context)
Start starts the application.
type BackgroundInfo ¶
type BackgroundInfo struct { Align string `xml:"align,attr"` Alpha int `xml:"bgalp,attr"` Color string `xml:"bgc,attr"` HasRecording int64 `xml:"hasrec,attr"` ImageAlpha int `xml:"ialp,attr"` IsVid bool `xml:"isvid,attr"` Tile bool `xml:"tile,attr"` UseImage bool `xml:"useimg,attr"` }
BackgroundInfo represents the background information of a user.
type Backoff ¶
type Backoff struct { Duration time.Duration // Duration represents the current backoff duration. MaxDuration time.Duration // MaxDuration is the maximum allowed backoff duration. // contains filtered or unexported fields }
Backoff represents a backoff mechanism with configurable duration and maximum duration.
type BanWord ¶
BanWord represents a banned word.
func (*BanWord) GetPartial ¶
GetPartial returns the partial banned words as a slice of strings.
func (*BanWord) SetPartial ¶
SetPartial sets the partial banned words.
type BirthDate ¶
BirthDate represents a birth date of a user.
func (*BirthDate) UnmarshalXML ¶
UnmarshalXML unmarshals the XML data into the BirthDate value.
type Callback ¶
Callback is a function type that represents a callback function for handling events.
type ChatFilter ¶
type ChatFilter struct {
Chats []string
}
ChatFilter represents a filter for chats.
func (*ChatFilter) Add ¶
func (f *ChatFilter) Add(chatName string)
Add adds a chat to the filter's list of chats.
func (*ChatFilter) And ¶
func (f *ChatFilter) And(filter Filter) Filter
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
func (*ChatFilter) Check ¶
func (f *ChatFilter) Check(event *Event) bool
Check checks if the event's group is in the filter's list of chats.
func (*ChatFilter) Not ¶
func (f *ChatFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
func (*ChatFilter) Or ¶
func (f *ChatFilter) Or(filter Filter) Filter
Or returns a new CombineFilter that combines the current filter with the provided filter using logical OR.
func (*ChatFilter) Remove ¶
func (f *ChatFilter) Remove(chatName string)
Remove removes a chat from the filter's list of chats.
func (*ChatFilter) Xor ¶
func (f *ChatFilter) Xor(filter Filter) Filter
Xor returns a new CombineFilter that combines the current filter with the provided filter using logical XOR.
type CombineFilter ¶
CombineFilter is a struct that represents the logical AND of two filters.
func (*CombineFilter) And ¶
func (f *CombineFilter) And(filter Filter) Filter
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
func (*CombineFilter) Check ¶
func (f *CombineFilter) Check(event *Event) bool
Check returns true if both the left and right filters return true.
func (*CombineFilter) Not ¶
func (f *CombineFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
func (*CombineFilter) Or ¶
func (f *CombineFilter) Or(filter Filter) Filter
Or returns a new CombineFilter that combines the current filter with the provided filter using logical OR.
func (*CombineFilter) Xor ¶
func (f *CombineFilter) Xor(filter Filter) Filter
Xor returns a new CombineFilter that combines the current filter with the provided filter using logical XOR.
type CommandHandler ¶
type CommandHandler struct { Callback Callback Filter Filter Commands []string // contains filtered or unexported fields }
CommandHandler is a struct that implements the Handler interface for handling command in message events.
func (*CommandHandler) Check ¶
func (ch *CommandHandler) Check(event *Event) bool
Check checks if the event is a command event that matches the prefix and command.
func (*CommandHandler) Invoke ¶
func (ch *CommandHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the command event.
type Config ¶
type Config struct { Username string `json:"username"` Password string `json:"password"` AnonName string `json:"anon_name"` Groups []string `json:"groups"` NameColor string `json:"name_color"` TextColor string `json:"text_color"` TextFont string `json:"text_font"` TextSize int `json:"text_size"` SessionID string `json:"session_id"` EnableBG bool `json:"enable_bg"` EnablePM bool `json:"enable_pm"` Debug bool `json:"debug"` Prefix string `json:"prefix"` }
Config represents a configuration object.
func LoadConfig ¶
LoadConfig loads the configuration from the specified file.
type Event ¶
type Event struct { Type EventType // The type of the event. IsPrivate bool // Indicates if the event is related to a private chat. Private *Private // The private chat associated with the event. Group *Group // The group associated with the event. User *User // The user associated with the event. Message *Message // The message associated with the event. Command string // The command associated with the event. WithArgument bool // Indicates if the command has an argument. Argument string // The argument associated with the command. Arguments []string // The arguments associated with the command. Participant *Participant // The participant associated with the event. FlagAdded int64 // The flags added in the event. FlagRemoved int64 // The flags removed in the event. Blocked *Blocked // The blocked user associated with the event. Unblocked *Unblocked // The unblocked user associated with the event. GroupInfo *GroupInfo // The group information associated with the event. ModGrantedAccess int64 // The granted moderator access level associated with the event. ModRevokedAccess int64 // The revoked moderator access level associated with the event. Error any // The error associated with the event. }
Event represents an event that can occur in the application.
type EventType ¶
type EventType int64
EventType represents the type of an event.
const ( // Event triggered when the application starts. OnStart EventType = 1 << iota // Event triggered when the application stops. OnStop // Event triggered when an error occurs. OnError // Event triggered when the bot joins a group. OnGroupJoined // Event triggered when the bot leaves a group. OnGroupLeft // Event triggered when the bot reconnects to a group. OnGroupReconnected // Event triggered when a user joins a group. OnJoin // Event triggered when a user logs in. OnLogin // Event triggered when a user logs out. OnLogout // Event triggered when a user leaves a group. OnLeave // Event triggered when the participant count in a group changes. OnParticipantCountChange // Event triggered when a message is received. OnMessage // Event triggered when a message is deleted. OnMessageDelete // Event triggered when message history is retrieved. OnMessageHistory // Event triggered when a message is updated. OnMessageUpdate // Event triggered when an announcement is received. OnAnnouncement // Event triggered when the group information is updated. OnUpdateGroupInfo // Event triggered when flags are updated. OnFlagUpdate // Event triggered when a moderator is added. OnModeratorAdded // Event triggered when a moderator is updated. OnModeratorUpdated // Event triggered when a moderator is removed. OnModeratorRemoved // Event triggered when all messages are cleared. OnClearAll // Event triggered when a user is banned. OnUserBanned // Event triggered when a user is unbanned. OnUserUnbanned // Event triggered when all users are unbanned. OnAllUserUnbanned // Event triggered when the bot connects to a private chat. OnPrivateConnected // Event triggered when the bot disconnects from a private chat. OnPrivateDisconnected // Event triggered when the bot reconnects to a private chat. OnPrivateReconnected // Event triggered when the bot is kicked off from a private chat. OnPrivateKickedOff // Event triggered when a private message is received. OnPrivateMessage // Event triggered when an offline private message is received. OnPrivateOfflineMessage // Event triggered when a friend becomes online in a private chat. OnPrivateFriendOnline // Event triggered when a friend becomes online in a private chat app. OnPrivateFriendOnlineApp // Event triggered when a friend goes offline in a private chat. OnPrivateFriendOffline // Event triggered when a friend becomes active in a private chat. OnPrivateFriendActive // Event triggered when a friend becomes idle in a private chat. OnPrivateFriendIdle // Event triggered when the user profile is updated. OnUpdateUserProfile )
Event types.
type Filter ¶
type Filter interface { Check(*Event) bool And(Filter) Filter Or(Filter) Filter Xor(Filter) Filter Not() Filter }
Filter is an interface that defines the methods for filtering events.
func NewChatFilter ¶
NewChatFilter returns a new `ChatFilter`.
func NewRegexFilter ¶
NewRegexFilter returns a new `RegexFilter`.
func NewUserFilter ¶
NewUserFilter returns a new `UserFilter`.
type FullProfile ¶
type FullProfile struct { XMLName xml.Name `xml:"mod"` Body QueryEscaped `xml:"body"` T string `xml:"t"` }
FullProfile represents a full profile of a user.
type Group ¶
type Group struct { App *Application // Reference to the application. Name string // The name of the group. AnonName string // The anonymous user name format. NameColor string // The color for displaying name in the message. TextColor string // The color for displaying text in the message. TextFont string // The font style for displaying text in the message. TextSize int // The font size for displaying text in the message. WsUrl string // The WebSocket URL for connecting to the group. Connected bool // Indicates if the group is currently connected. Version [2]int // The version of the group. Owner string // The owner of the group. SessionID string // The session ID for the group. LoggedIn bool // Indicates if the user is logged in to the group. LoginName string // The login name of the user. LoginTime time.Time // The time when the user logged in. TimeDiff time.Duration // The time difference between the server and client. LoginIp string // The IP address of the user. Moderators SyncMap[string, int64] // Map of moderators and their access levels. Flag int64 // The flag value for the group. Channel int64 // The channel flag of the group. Restrict time.Time // The time when the group is restricted from the flood ban and auto moderation. RateLimit time.Duration // The rate limit duration for sending messages. RateLimited time.Time // The time when the group is rate-limited. MaxMessageLength int // The maximum allowed length of a message. PremiumExpireAt time.Time // The time when the premium membership expires. Messages OrderedSyncMap[string, *Message] // Ordered map of messages history in the group. TempMessages SyncMap[string, *Message] // Map of temporary messages in the group. TempMessageIds SyncMap[string, string] // Map of temporary message IDs in the group. Participants SyncMap[string, *Participant] // Map of participants in the group. Invoke `g.GetParticipantsStart` to initiate the participant feeds. ParticipantCount int64 // The total count of participants in the group. UserCount int // The count of registered users in the group. AnonCount int // The count of anonymous users in the group. // contains filtered or unexported fields }
Group represents a chat group with various properties and state.
func (*Group) AddModerator ¶
AddModerator adds a moderator to the group with the specified username and access level.
func (*Group) Connect ¶
Connect establishes a connection to the server. It returns an error if the connection cannot be established.
func (*Group) Disconnect ¶
func (g *Group) Disconnect()
Disconnect gracefully closes the connection to the server.
func (*Group) GetAnnouncement ¶
GetAnnouncement retrieves the announcement settings for the group.
func (*Group) GetBanList ¶
GetBanList retrieves a list of blocked users (ban list) for the group. The offset can be set to zero time to retrieve the newest result. The returned order is from newer to older.
func (*Group) GetBanWords ¶
GetBanWords retrieves the banned word settings for the group.
func (*Group) GetContext ¶
GetContext returns the context of the private chat.
func (*Group) GetLastUserMessage ¶
GetLastUserMessage retrieves the last message sent by the specified username in the group.
func (*Group) GetModActions ¶
GetModActions retrieves a list of moderator actions (mod actions) for the group. The `dir` can be either "prev" to go earlier or "next" to go to the latest. The `offset` corresponds to the ID of the earlier-1 or latest+1 `ModAction.ID`.
func (*Group) GetParticipantsStart ¶
func (g *Group) GetParticipantsStart() (p *SyncMap[string, *Participant], err error)
GetParticipantsStart initiates the `participant` event feeds and returns the current participants. The `participant` event will be triggered when there is user activity, such as joining, logging out, logging in, or leaving.
func (*Group) GetParticipantsStop ¶
GetParticipantsStop stops the participant event feeds. This will leave g.Participants, g.UserCount, g.AnonCount out of date.
func (*Group) GetPremiumInfo ¶
GetPremiumInfo retrieves the premium status and expiration time for the group. This function would activate server validation for the premium status. For example, the message background and media won't activate before this command is sent.
func (*Group) GetRateLimit ¶
GetRateLimit retrieves the rate limit settings for the group.
func (*Group) GetUnbanList ¶
GetUnbanList retrieves a list of unblocked users (unban list) for the group. The `offset` is taken from the earliest time in the previous result or zero `time.Time`. The `amount` corresponds to the desired number of results.
func (*Group) IsRestricted ¶
IsRestricted checks if the group is restricted. The restriction can originate from either a flood ban or a rate limit.
func (*Group) Login ¶
Login logs in to the group with the provided username and password. If the password is an empty string, it will log in as the named anon instead.
func (*Group) ProfileRefresh ¶
ProfileRefresh notifies the server to refresh the profile.
func (*Group) PropagateEvent ¶
PropagateEvent propagates the WebSocket frame back to the listener goroutine. It is utilized when the `g.SyncSend` callback receives unwanted frames.
func (*Group) RemoveModerator ¶
RemoveModerator removes the specified moderator from the group.
func (*Group) SearchBannedUser ¶
SearchBannedUser searches for a banned user in the group's ban list. The query can be either a user name or an IP address.
func (*Group) Send ¶
Send will join the `args` with a ":" separator and then send it to the server asynchronously.
func (*Group) SendMessage ¶
SendMessage sends the `text` and returns the sent `*Message`. In case of an error, including flood ban, auto moderation, rate limit, as well as login, proxy, and verification restrictions, the corresponding error will be returned.
func (*Group) SendMessageChunked ¶
SendMessage sends the chunked `text` with a size of `chunkSize` and returns the sent `[]*Message`. In the event of an error, the already sent messages will be returned along with the error for the unsent message.
func (*Group) SetAnnouncement ¶
SetAnnouncement sets the announcement settings for the group.
func (*Group) SetBackground ¶
SetBackground sets the background status of the group. If enable is true, it enables the background feature for the group. If enable is false, it disables the background feature for the group.
func (*Group) SetBanWords ¶
SetBanWords sets the banned word settings for the group.
func (*Group) SetMedia ¶
SetMedia sets the media status of the group. If enable is true, it enables the media feature for the group. If enable is false, it disables the media feature for the group.
func (*Group) SetRateLimit ¶
SetRateLimit sets the rate limit interval for the group.
func (*Group) SyncSend ¶
SyncSend will send the `args` and wait until receiving the correct reply or until timeout (default to 5 seconds). For more information, refer to the documentation of `g.SyncSendWithTimeout`.
func (*Group) SyncSendWithTimeout ¶
func (g *Group) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
SyncSend will send the `args` and wait until receiving the correct reply or until timeout. First, a `g.takeOver` request will be made and it will wait until the listener goroutine catches it. Then, the `args` will be sent to the server. Each time a frame is received, the `callback` function is invoked and passed the frame. The `callback` should return `true` if a correct frame is acquired, and `false` otherwise.
func (*Group) UpdateGroupFlag ¶
UpdateGroupFlag updates the group's flag by adding and removing specific flags.
type GroupInfo ¶
GroupInfo represents a group info.
func (*GroupInfo) GetMessage ¶
GetDescription returns the description of the group.
type Handler ¶
Handler is an interface that defines the methods for handling events.
func NewCommandHandler ¶
NewCommandHandler returns a new `CommandHandler`.
func NewMessageHandler ¶
NewMessageHandler returns a new `MessageHandler`.
type KeyValue ¶
KeyValue represents a key-value pair This is a function helper for "emod" ModAction parsing.
type Location ¶
type Location struct { Country string `xml:"c,attr"` G string `xml:"g,attr"` Latitude float64 `xml:"lat,attr"` Longitude float64 `xml:"lon,attr"` Text string `xml:",chardata"` }
Location represents the location information of a user.
type Message ¶
type Message struct { Group *Group Private *Private IsPrivate bool User *User Text string RawText string UserID string ID string DeleteID string ModerationID string UserIP string Time time.Time ReceivedTime time.Time Flag int64 FromSelf bool FromAnon bool AnonSeed string }
Message represent message come from group and private chat.
func ParseAnnouncement ¶
ParseAnnouncement parses a group announcement data and returns a Message object.
func ParseGroupMessage ¶
ParseGroupMessage parses a group message data and returns a Message object.
func ParsePrivateMessage ¶
ParsePrivateMessage parses a private message data and returns a Message object.
func (*Message) HasBackground ¶
HasBackground checks if the message has background flag.
func (*Message) HasPremium ¶
HasPremium checks if the message has premium flag.
type MessageHandler ¶
MessageHandler is a struct that implements the Handler interface for handling message events.
func (*MessageHandler) Check ¶
func (mh *MessageHandler) Check(event *Event) bool
Check checks if the event is a message event.
func (*MessageHandler) Invoke ¶
func (mh *MessageHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the message event.
type MiniProfile ¶
type MiniProfile struct { XMLName xml.Name `xml:"mod"` Body QueryEscaped `xml:"body"` Gender string `xml:"s"` Birth BirthDate `xml:"b"` Location Location `xml:"l"` Premium PremiumDate `xml:"d"` }
MiniProfile represents a mini profile of a user.
type ModAction ¶
type ModAction struct { ID int Type string User string IP string Target string Time time.Time Extra string }
ModAction represents a moderation action.
func ParseModActions ¶
ParseModActions parses a string data and returns a slice of ModAction objects
func (*ModAction) ExtraAsBool ¶
ExtraAsBool returns the Extra field as a boolean.
func (*ModAction) ExtraAsInt ¶
ExtraAsInt returns the Extra field as an int64.
func (*ModAction) ExtraAsSliceInt ¶
ExtraAsSliceInt returns the Extra field as a slice of int64.
func (*ModAction) ExtraAsSliceInterface ¶
func (ma *ModAction) ExtraAsSliceInterface() (ret []interface{})
ExtraAsSliceInterface returns the Extra field as a slice of interface{}.
func (*ModAction) ExtraBanWord ¶
ExtraBanWord returns the Extra field as a BanWord.
func (*ModAction) ExtraDescription ¶
ExtraDescription returns the Extra field as a GroupInfo.
type MyChatGroups ¶
type MyChatGroups struct { RecentGroups [][2]string `json:"recent_groups"` UnreadMessages int `json:"n_msg"` Groups [][2]string `json:"groups"` }
MyChatGroups represents the created & recent chat groups of the user. It also provides the number of unread private message.
func (MyChatGroups) GetGroups ¶
func (mg MyChatGroups) GetGroups() map[string]string
GetGroups returns the map of all chat groups.
func (MyChatGroups) GetRecentGroups ¶
func (mg MyChatGroups) GetRecentGroups() map[string]string
GetRecentGroups returns the map of recent chat groups.
type NotFilter ¶
type NotFilter struct {
Base Filter
}
NotFilter is a struct that represents the logical NOT of a filter.
func (*NotFilter) And ¶
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
type OrderedSyncMap ¶
type OrderedSyncMap[K comparable, V any] struct { sync.RWMutex K []K M map[K]V }
OrderedSyncMap is a synchronized map that maintains the order of keys.
func NewOrderedSyncMap ¶
func NewOrderedSyncMap[K comparable, V any]() OrderedSyncMap[K, V]
NewOrderedSyncMap creates a new instance of OrderedSyncMap.
func (*OrderedSyncMap[K, V]) Clear ¶
func (sm *OrderedSyncMap[K, V]) Clear()
Clear removes all key-value pairs from the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) Del ¶
func (sm *OrderedSyncMap[K, V]) Del(key K)
Del removes the key-value pair with the specified key from the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) Get ¶
func (sm *OrderedSyncMap[K, V]) Get(key K) (val V, ok bool)
Get retrieves the value associated with the specified key from the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) GobDecode ¶
func (sm *OrderedSyncMap[K, V]) GobDecode(data []byte) error
GobDecode decodes the OrderedSyncMap using Gob.
func (*OrderedSyncMap[K, V]) GobEncode ¶
func (sm *OrderedSyncMap[K, V]) GobEncode() ([]byte, error)
GobEncode encodes the OrderedSyncMap using Gob.
func (*OrderedSyncMap[K, V]) Keys ¶
func (sm *OrderedSyncMap[K, V]) Keys() []K
Keys returns a slice of keys in the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) Len ¶
func (sm *OrderedSyncMap[K, V]) Len() int
Len returns the number of key-value pairs in the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) Range ¶
func (sm *OrderedSyncMap[K, V]) Range(fun func(K, V) bool)
Range iterates over each key-value pair in the OrderedSyncMap and calls the specified function. If the function returns false, the iteration stops.
func (*OrderedSyncMap[K, V]) RangeReversed ¶
func (sm *OrderedSyncMap[K, V]) RangeReversed(fun func(K, V) bool)
RangeReversed iterates over each key-value pair in the OrderedSyncMap in reverse order and calls the specified function. If the function returns false, the iteration stops.
func (*OrderedSyncMap[K, V]) Set ¶
func (sm *OrderedSyncMap[K, V]) Set(key K, val V)
Set adds or updates a key-value pair in the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) SetFront ¶
func (sm *OrderedSyncMap[K, V]) SetFront(key K, val V)
SetFront adds or updates a key-value pair at the front of the OrderedSyncMap.
func (*OrderedSyncMap[K, V]) TrimFront ¶
func (sm *OrderedSyncMap[K, V]) TrimFront(length int)
TrimFront trims the front part of the OrderedSyncMap to the specified length. It modifies the OrderedSyncMap in place, removing elements from the beginning of the map until the desired length is reached.
type Participant ¶
Participant represents a group participant object.
type PeopleQuery ¶
type PeopleQuery struct { AgeFrom int // Minimum age AgeTo int // Maximum age Gender string // Gender (B, M, F, N) Username string // Username Radius int // Radius Latitude string // Latitude Longtitude string // Longitude Online bool // Online status Offset int // Offset Amount int // Amount }
PeopleQuery represents a query for searching people.
func (*PeopleQuery) GetForm ¶
func (pq *PeopleQuery) GetForm() (form url.Values)
GetForm returns the URL-encoded form values for the PeopleQuery.
func (*PeopleQuery) NextOffset ¶
func (pq *PeopleQuery) NextOffset()
NextOffset updates the offset to retrieve the next set of results.
type Persistence ¶
type Persistence struct { Filename string // File name for the data. Interval time.Duration // Interval for auto-saving. BotData SyncMap[string, any] // Map to store bot-related data. ChatData SyncMap[string, *SyncMap[string, any]] // Map to store chat-related data. // contains filtered or unexported fields }
Persistence is responsible for loading and saving data to a file periodically. If the filename is set to an empty string, it will disable auto-saving. If the interval is set to less than 1 minute, it will be adjusted to 30 minutes.
func (*Persistence) Close ¶
func (p *Persistence) Close() error
Close stops the auto save routine and saves the data to the file.
func (*Persistence) DelChatData ¶
func (p *Persistence) DelChatData(key string)
DelChatData deletes the ChatData for the given key.
func (*Persistence) GetBotData ¶
func (p *Persistence) GetBotData() *SyncMap[string, any]
GetBotData returns a pointer to the BotData.
func (*Persistence) GetChatData ¶
func (p *Persistence) GetChatData(key string) *SyncMap[string, any]
GetChatData returns a pointer to the ChatData for the given key. If the ChatData does not exist, it creates a new one and returns it.
func (*Persistence) Initialize ¶
func (p *Persistence) Initialize() error
Initialize initializes the Persistence struct by loading the data from the file and starting the auto save routine.
func (*Persistence) Load ¶
func (p *Persistence) Load() error
Load loads the data from the file into the Persistence struct.
func (*Persistence) Save ¶
func (p *Persistence) Save() error
Save saves the data from the Persistence struct to the file.
type PremiumDate ¶
PremiumDate represents a premium date of a user.
func (*PremiumDate) UnmarshalXML ¶
func (c *PremiumDate) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML unmarshals the XML data into the PremiumDate value.
type Private ¶
type Private struct { App *Application // Reference to the application. Name string // The name of the group. NameColor string // The color for displaying name in the message. TextColor string // The color for displaying text in the message. TextFont string // The font style for displaying text in the message. TextSize int // The font size for displaying text in the message. WsUrl string // The WebSocket URL for connecting to the PM server. Connected bool // Indicates if the PM server is currently connected. LoginName string // The login name of the user. SessionID string // The session ID for the PM server. LoginTime time.Time // The time when the user logged in. TimeDiff time.Duration // The time difference between the server and client (serverTime - clientTime). IsIdle bool // Indicates whether there has been no activity within 1 minute (e.g., sending a message). // contains filtered or unexported fields }
Private represents a private message with various properties and state.
func (*Private) AddFriend ¶
func (p *Private) AddFriend(username string) (status UserStatus, err error)
AddFriend adds a username to the friend list.
func (*Private) Connect ¶
Connect establishes a connection to the server. It returns an error if the connection cannot be established.
func (*Private) ConnectUser ¶
func (p *Private) ConnectUser(username string) (status UserStatus, err error)
ConnectUser opens a chat session with the username.
func (*Private) Disconnect ¶
func (p *Private) Disconnect()
Disconnect gracefully closes the connection to the PM server.
func (*Private) DisconnectUser ¶
DisconnectUser closes the chat session with the username.
func (*Private) GetBlocked ¶
GetBlocked retrieves the list of blocked users.
func (*Private) GetContext ¶
GetContext returns the context of the private chat.
func (*Private) GetFriendList ¶
func (p *Private) GetFriendList() (friendlist []UserStatus, err error)
GetFriendList retrieves the list of friends with their corresponding status.
func (*Private) GetPresence ¶
func (p *Private) GetPresence(usernames []string) (statuslist []UserStatus, err error)
GetPresence retrieves the status of multiple usernames. If the user is offline, the corresponding `UserStatus.Time` is not accurate.
func (*Private) GetSettings ¶
func (p *Private) GetSettings() (setting PrivateSetting, err error)
GetSettings retrieves the current settings.
func (*Private) ProfileRefresh ¶
ProfileRefresh notifies the server to refresh the profile.
func (*Private) PropagateEvent ¶
PropagateEvent propagates the WebSocket frame back to the listener goroutine. It is utilized when the `p.SyncSend` callback receives unwanted frames.
func (*Private) RemoveFriend ¶
RemoveFriend removes the username from the friend list.
func (*Private) Send ¶
Send will join the `args` with a ":" separator and then send it to the server asynchronously.
func (*Private) SendMessage ¶
SendMessage sends a private message with the specified text to the username.
func (*Private) SetSettings ¶
func (p *Private) SetSettings(setting PrivateSetting) (err error)
SetSettings updates the settings with the provided values.
func (*Private) SyncSend ¶
SyncSend will send the `args` and wait until receiving the correct reply or until timeout (default to 5 seconds). For more information, refer to the documentation of `p.SyncSendWithTimeout`.
func (*Private) SyncSendWithTimeout ¶
func (p *Private) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
SyncSendWithTimeout will send the `args` and wait until receiving the correct reply or until timeout. First, a `p.takeOver` request will be made and it will wait until the listener goroutine catches it. Then, the `args` will be sent to the server. Each time a frame is received, the `callback` function is invoked and passed the frame. The `callback` should return `true` if a correct frame is acquired, and `false` otherwise.
func (*Private) Track ¶
func (p *Private) Track(username string) (status UserStatus, err error)
Track retrieves the online status of the username.
func (*Private) WentActive ¶
func (p *Private) WentActive()
WentActive notifies the server that the user went active.
type PrivateSetting ¶
UserStatus represents private message settings.
type QueryEscaped ¶
type QueryEscaped string
QueryEscaped represents a query-escaped string.
func (*QueryEscaped) UnmarshalXML ¶
func (c *QueryEscaped) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
UnmarshalXML unmarshals the XML data into the QueryEscaped value.
type RegexFilter ¶
RegexFilter represents a Message filter based on a regular expression pattern.
func (*RegexFilter) And ¶
func (f *RegexFilter) And(filter Filter) Filter
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
func (*RegexFilter) Check ¶
func (f *RegexFilter) Check(event *Event) bool
Check checks if the event matches the regular expression pattern.
func (*RegexFilter) Not ¶
func (f *RegexFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
func (*RegexFilter) Or ¶
func (f *RegexFilter) Or(filter Filter) Filter
Or returns a new CombineFilter that combines the current filter with the provided filter using logical OR.
func (*RegexFilter) Xor ¶
func (f *RegexFilter) Xor(filter Filter) Filter
Xor returns a new CombineFilter that combines the current filter with the provided filter using logical XOR.
type SyncMap ¶
type SyncMap[K comparable, V any] struct { sync.RWMutex M map[K]V }
SyncMap is a synchronized map that can be accessed concurrently.
func NewSyncMap ¶
func NewSyncMap[K comparable, V any]() SyncMap[K, V]
NewSyncMap creates a new instance of SyncMap.
func (*SyncMap[K, V]) Clear ¶
func (sm *SyncMap[K, V]) Clear()
Clear removes all key-value pairs from the SyncMap.
func (*SyncMap[K, V]) Del ¶
func (sm *SyncMap[K, V]) Del(key K)
Del removes the key-value pair with the specified key from the SyncMap.
func (*SyncMap[K, V]) Get ¶
Get retrieves the value associated with the specified key from the SyncMap.
func (*SyncMap[K, V]) Keys ¶
func (sm *SyncMap[K, V]) Keys() (keys []K)
Keys returns a slice of keys in the SyncMap.
type Transport ¶
type Transport struct { Transport http.RoundTripper // Transport is the underlying RoundTripper. Headers map[string]string // Headers contains custom headers to be added to the requests. }
Transport is a custom RoundTripper implementation.
type TypeHandler ¶
TypeHandler is a struct that implements the Handler interface for handling events of a specific type.
func (*TypeHandler) Check ¶
func (th *TypeHandler) Check(event *Event) bool
Check checks if the event is of the specified type.
func (*TypeHandler) Invoke ¶
func (th *TypeHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the event of the specified type.
type Unblocked ¶
type Unblocked struct { IP string ModerationID string Target string Unblocker string Time time.Time }
Unblocked represents a group unbanned user.
type UserFilter ¶
type UserFilter struct {
Users []string
}
UserFilter represents a filter for users.
func (*UserFilter) Add ¶
func (f *UserFilter) Add(userName string)
Add adds a user to the filter's list of users.
func (*UserFilter) And ¶
func (f *UserFilter) And(filter Filter) Filter
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
func (*UserFilter) Check ¶
func (f *UserFilter) Check(event *Event) bool
Check checks if the event's user is in the filter's list of users.
func (*UserFilter) Not ¶
func (f *UserFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
func (*UserFilter) Or ¶
func (f *UserFilter) Or(filter Filter) Filter
Or returns a new CombineFilter that combines the current filter with the provided filter using logical OR.
func (*UserFilter) Remove ¶
func (f *UserFilter) Remove(userName string)
Remove removes a user from the filter's list of users.
func (*UserFilter) Xor ¶
func (f *UserFilter) Xor(filter Filter) Filter
Xor returns a new CombineFilter that combines the current filter with the provided filter using logical XOR.
type UserStatus ¶
UserStatus represents online status of a user.
type WebSocket ¶
type WebSocket struct { Connected bool Events chan string OnError func(error) // contains filtered or unexported fields }
WebSocket represents a WebSocket connection. It implements `golang.org/x/net/websocket` under the hood and wraps it into a channel, allowing it to be select-able along with other channels.