Documentation ¶
Overview ¶
chadango package is a modern framework designed to facilitate the creation and management of bots for the Chatango messaging platform. Written in Go, this package leverages Go's concurrency capabilities to provide efficient and robust bot interactions.
Key Features:
- Chatango Client: A client for connecting to and interacting with the Chatango messaging platform.
- Connection Management: Functions to establish and terminate connections securely.
- Concurrency Support: Utilizes Go's synchronization mechanisms to ensure thread-safe operations.
- Customizable API: Provides a flexible API structure for handling various Chatango functionalities.
- Error Handling: Implements mechanisms for managing errors and maintaining stable connections.
Usage Example:
package main import ( "context" dango "github.com/n0h4rt/chadango" ) func main() { config := &dango.Config{ Username: "username", Password: "password", Prefix: ".", EnableBG: true, EnablePM: true, Groups: []string{"groupchat1", "groupchat2"}, } app := dango.New(config) // add handlers app.Initialize() ctx := context.Background() app.Start(ctx) // The `app.Park()` call is blocking, use CTRL + C to stop the application. // Use this if it is the top layer application. app.Park() }
The chadango package aims to streamline the development of Chatango bots, providing a solid foundation for building advanced and scalable messaging solutions.
Index ¶
- Constants
- Variables
- func BoolZeroOrOne(b bool) string
- func ComputeFlagChanges(oldFlags, newFlags int64) (addedFlags, removedFlags int64)
- func Contains[T comparable](arr []T, item T) bool
- func CreateAnonSeed(name string, sid int) (seed int)
- func FileExists(filename string) bool
- func GetAnonName(seed, sid int) (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)
- func UsernameToURL(url, username string) string
- type APIClient
- type Application
- func (app *Application) AddErrorHandler(handler Handler) *Application
- func (app *Application) AddHandler(handler Handler) *Application
- func (app *Application) ConnectPM() error
- func (app *Application) DisconnectPM()
- func (app *Application) GetContext() context.Context
- func (app *Application) Initialize() *Application
- func (app *Application) JoinGroup(groupName string) error
- func (app *Application) LeaveGroup(groupName string) error
- func (app *Application) Park()
- func (app *Application) PrivateAPI() *PrivateAPI
- func (app *Application) PublicAPI() *PublicAPI
- func (app *Application) RemoveErrorHandler(handler Handler) *Application
- func (app *Application) RemoveHandler(handler Handler) *Application
- func (app *Application) Start(ctx context.Context) *Application
- func (app *Application) Stop()
- func (app *Application) UsePersistence(persistence Persistence) *Application
- 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 FontFamily
- type FullProfile
- type GobPersistence
- func (p *GobPersistence) Close() error
- func (p *GobPersistence) DelChatData(key string)
- func (p *GobPersistence) GetBotData() *SyncMap[string, any]
- func (p *GobPersistence) GetChatData(key string) *SyncMap[string, any]
- func (p *GobPersistence) Initialize() error
- func (p *GobPersistence) Load() error
- func (p *GobPersistence) Runner(ctx context.Context)
- func (p *GobPersistence) Save() error
- 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, err error)
- func (g *Group) Send(args ...string) error
- func (g *Group) SendMessage(text string, a ...any) (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) 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(callback func(string) bool, args ...string) error
- func (g *Group) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
- func (g *Group) UnbanAll() (amount int, 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() (c MessageChannel)
- func (m *Message) Delete() error
- func (m *Message) DeleteAll() error
- func (m *Message) HasBackground() bool
- func (m *Message) HasMedia() bool
- func (m *Message) HasModIcon() bool
- func (m *Message) HasPremium() bool
- func (m *Message) HasStaffIcon() bool
- func (m *Message) IsCensored() bool
- func (m *Message) IsInModChannel() bool
- func (m *Message) NameColor() string
- func (m *Message) Reply(text string, a ...any) (*Message, error)
- func (m *Message) TextStyle() (textColor, textFont string, textSize int)
- type MessageBackground
- type MessageChannel
- type MessageHandler
- type MessageStyle
- 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 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 PeopleResult
- type Persistence
- 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, a ...any) (err error)
- func (p *Private) SetSettings(setting PrivateSetting) (err error)
- func (p *Private) SyncSend(cb func(string) bool, args ...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() (err error)
- func (p *Private) WentIdle() error
- type PrivateAPI
- func (p *PrivateAPI) GetCookie(name string) (string, bool)
- func (p *PrivateAPI) GetCreatedGroups() map[string]string
- func (p *PrivateAPI) GetGCMID() string
- func (p *PrivateAPI) GetGCMToken() string
- func (p *PrivateAPI) GetMsgBgImage() string
- func (p *PrivateAPI) GetRecentGroups() map[string]string
- func (p *PrivateAPI) GetUnreadMsgCount() int
- func (p *PrivateAPI) IsLoggedIn() bool
- func (p *PrivateAPI) Login() error
- func (p *PrivateAPI) RegisterGCM() (err error)
- func (p *PrivateAPI) RetrieveMsgBg() error
- func (p *PrivateAPI) RetrieveMsgStyle() error
- func (p *PrivateAPI) RetrieveTokenGCM() (err error)
- func (p *PrivateAPI) RetrieveUpdate() (err error)
- func (p *PrivateAPI) SearchPeople(query PeopleQuery) (result []PeopleResult, err error)
- func (p *PrivateAPI) SetGCMID(gcmID string)
- func (p *PrivateAPI) SetGCMToken(token string)
- func (p *PrivateAPI) UnregisterGCM() (err error)
- func (p *PrivateAPI) UpdateMsgBg() (err error)
- func (p *PrivateAPI) UpdateMsgStyle() (err error)
- func (p *PrivateAPI) UploadImage(filename string, image io.Reader) (img UploadedImage, err error)
- func (p *PrivateAPI) UploadMsgBgImage(filename string, image io.Reader) (err error)
- type PrivateSetting
- type PublicAPI
- func (p *PublicAPI) CheckUsername(username string) (ok bool, notOkReasons []string, err error)
- func (p *PublicAPI) GetBackground(username string) (background MessageBackground, err error)
- func (p *PublicAPI) GetFullProfile(username string) (profile FullProfile, err error)
- func (p *PublicAPI) GetMiniProfile(username string) (profile MiniProfile, err error)
- func (p *PublicAPI) GetStyle(username string) (style MessageStyle, err error)
- func (p *PublicAPI) IsGroup(groupname string) (answer bool, err error)
- 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 UploadedImage
- 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 )
const ( API_LOGIN = "https://chatango.com/login" API_GRP_LIST_UPD = "https://chatango.com/groupslistupdate" API_MSG_BG_IMG = "https://ust.chatango.com/profileimg/%s/%s/%s/msgbg.jpg" API_MSG_BG_XML = "https://ust.chatango.com/profileimg/%s/%s/%s/msgbg.xml" API_UPD_MSG_BG = "https://chatango.com/updatemsgbg" API_SEARCH_PEOPLE = "https://chatango.com/search" API_UPLOAD_IMG = "https://chatango.com/uploadimg" API_MSG_STYLE_JSON = "https://ust.chatango.com/profileimg/%s/%s/%s/msgstyles.json" API_UPD_MSG_STYLE = "https://chatango.com/updatemsgstyles" API_SET_TOKEN_GCM = "https://chatango.com/settokenapp" API_REG_GCM = "https://chatango.com/updategcm" API_UNREG_GCM = "https://chatango.com/unregistergcm" API_UM_THUMB = "https://ust.chatango.com/um/%s/%s/%s/img/t_%%d.jpg" API_UM_LARGE = "https://ust.chatango.com/um/%s/%s/%s/img/l_%%d.jpg" API_CHECK_USER = "https://st.chatango.com/script/namecheckeraccsales" API_CHECK_GROUP = "https://chatango.com/checkname" API_MINI_XML = "https://ust.chatango.com/profileimg/%s/%s/%s/mod1.xml" API_FULL_XML = "https://ust.chatango.com/profileimg/%s/%s/%s/mod2.xml" API_PHOTO_FULL_IMG = "https://fp.chatango.com/profileimg/%s/%s/%s/full.jpg" )
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("retry ends") ErrCLimited = errors.New("climited") ErrLoginFailed = errors.New("failed to login") ErrNoArgument = errors.New("no argument") ErrTimeout = errors.New("timeout") ErrRateLimited = errors.New("rate limited") 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") ErrOfflineLimit = errors.New("offline message limit") ErrBadAlias = errors.New("bad alias") ErrBadLogin = errors.New("bad login") ErrRequestFailed = errors.New("request 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]+)?">`) NameFontTag = regexp.MustCompile(`<[nf]\s?[^>]*>`) PrivateFontStyleRe = regexp.MustCompile(`<g x(\d+)?s([\da-fA-F]+)?="([\d\w]+)?">`) // Go does not support negative lookahead `<(?!br\s*\/?>).*?>`. // This alternative will match either the `<br>` and `<br/>` tags (captured in group 1) // or any other HTML tags (captured in group 2). // Then the `ReplaceAllString(text, "$1")` method will then keep the content matched by group 1 // and remove the content matched by group 2. HtmlTagRe = regexp.MustCompile(`(<br\s*\/?>)|(<[^>]+>)`) )
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 BoolZeroOrOne ¶ added in v0.0.2
BoolZeroOrOne returns either "0" or "1"
The function returns "0" if the provided boolean value is false, and "1" if it is true.
Args:
- b: The boolean value to convert.
Returns:
- string: "0" if the boolean value is false, and "1" if it is true.
func ComputeFlagChanges ¶
ComputeFlagChanges computes the flag changes between the oldFlags and newFlags values.
The function calculates the added and removed flags by comparing the old and new flag values. It returns two integers representing the added and removed flags.
Args:
- oldFlags: The old flag value.
- newFlags: The new flag value.
Returns:
- int64: The added flags.
- int64: The removed flags.
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.
The function iterates through the array and compares each element with the specified item. It returns true if the item is found in the array, otherwise false.
Args:
- arr: The array to search in.
- item: The item to search for.
Returns:
- bool: True if the item is found in the array, otherwise false.
func CreateAnonSeed ¶
CreateAnonSeed creates an anonymous seed using the provided name and sid.
The function generates an anonymous seed value based on the provided name and sid. It extracts the numerical part from the name (if it starts with "anon") and combines it with the sid to create a unique seed.
Args:
- name: The name of the user.
- sid: The session ID of the user.
Returns:
- int: The generated anonymous seed value.
func FileExists ¶
FileExists checks whether the specified file exists.
Args:
- filename: The name of the file to check.
Returns:
- bool: True if the file exists, otherwise false.
func GetAnonName ¶
GetAnonName generates an anonymous name using the provided seed and sid.
The function uses a specific algorithm to generate an anonymous name based on the provided seed and sid values. It ensures that the generated name starts with "anon" followed by a unique numerical identifier.
Args:
- seed: The seed value used for generating the anonymous name.
- sid: The session ID of the user.
Returns:
- string: The generated anonymous name.
func GetServer ¶
GetServer returns the server URL for a given name.
The function uses a weighted round-robin algorithm to select a server based on a calculated modulus ratio. It takes the name as input and calculates a ratio based on the first and second halves of the name. This ratio is then used to determine the server with the highest weight.
Args:
- name: The name of the chat room.
Returns:
- string: The server URL for the given name.
func IsDigit ¶
IsDigit checks whether the provided string represents a digit.
The function attempts to parse the string as an integer. If the parsing is successful, it returns true, otherwise false.
Args:
- strnum: The string to check.
Returns:
- bool: True if the string represents a digit, otherwise false.
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.
The function takes a variable number of arguments and returns the largest value among them.
Args:
- a: The first number to compare.
- b: The remaining numbers to compare.
Returns:
- T: 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.
The function takes a variable number of arguments and returns the smallest value among them.
Args:
- a: The first number to compare.
- b: The remaining numbers to compare.
Returns:
- T: The minimum value among the provided numbers.
func ParseTime ¶
ParseTime parses the provided string representation of time into a time.Time value.
The function splits the string into seconds and nanoseconds parts, pads the nanoseconds part with zeros to ensure 6 digits, and then converts the values into int64 before creating a time.Time object using time.Unix.
Args:
- strtime: The string representation of time.
Returns:
- time.Time: The parsed time.Time object.
- error: An error if the parsing fails.
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.
The function iterates through the array and removes the first occurrence of the specified item. It returns the modified array without the removed item.
Args:
- arr: The array to remove the item from.
- item: The item to remove.
Returns:
- []T: The modified array without the removed item.
func SaveConfig ¶
SaveConfig saves the configuration to the specified file.
The function marshals the provided Config struct into JSON format and writes it to the specified file. It returns any error encountered during saving.
Args:
- filename: The name of the configuration file.
- config: The Config struct to save.
Returns:
- error: An error if the saving fails.
func SplitTextIntoChunks ¶
SplitTextIntoChunks splits the provided text into chunks of the specified size.
The function splits the text into chunks of the specified size, ensuring that words are not split across chunks. It returns a slice of strings representing the chunks.
Args:
- text: The text to split into chunks.
- chunkSize: The maximum size of each chunk.
Returns:
- []string: A slice of strings representing the chunks.
func UsernameToURL ¶ added in v0.0.3
UsernameToURL generates a URL for a Chatango resource based on the provided URL template and username.
The function takes a URL template and a username as input and replaces placeholders in the template with the username's parts. It returns the generated URL.
Args:
- url: The URL template with placeholders.
- username: The username to use for replacing placeholders.
Returns:
- string: The generated URL.
Types ¶
type APIClient ¶ added in v0.0.3
type APIClient struct {
// contains filtered or unexported fields
}
APIClient represents a client for the Chatango API.
func (*APIClient) Get ¶ added in v0.0.3
Get sends a GET request to the specified URL with the provided parameters.
Args:
- url: The URL to send the GET request to.
- param: The URL parameters to include in the request.
Returns:
- *http.Response: The HTTP response.
- error: An error if the request fails.
func (*APIClient) PostForm ¶ added in v0.0.3
PostForm sends a POST request with form data to the specified URL.
Args:
- url: The URL to send the POST request to.
- data: The form data to include in the POST request.
Returns:
- *http.Response: The HTTP response.
- error: An error if the request fails.
func (*APIClient) PostMultipart ¶ added in v0.0.3
PostMultipart sends a POST request with body and its content-type to the specified URL.
Args:
- url: The URL to send the POST request to.
- body: The body of the POST request.
- ctype: The content type of the POST request.
Returns:
- *http.Response: The HTTP response.
- error: An error if the request fails.
type Application ¶
type Application struct { Config *Config // Config holds the configuration for the pplication. 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.
It provides methods for managing the application's lifecycle, including initialization, starting, stopping, connecting to groups and private messages, and handling events and errors. The application also manages data persistence and provides access to the public and private APIs.
func New ¶
func New(config *Config) *Application
New creates a new instance of the Application with the provided configuration.
Args:
- config: The configuration for the application.
Returns:
- *Application: A new instance of the Application.
func (*Application) AddErrorHandler ¶ added in v0.0.3
func (app *Application) AddErrorHandler(handler Handler) *Application
AddErrorHandler adds a new error handler to the application.
Args:
- handler: The error handler to add to the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) AddHandler ¶
func (app *Application) AddHandler(handler Handler) *Application
AddHandler adds a new handler to the application.
Args:
- handler: The handler to add to the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) ConnectPM ¶
func (app *Application) ConnectPM() error
ConnectPM connects to private messages.
Returns:
- error: An error if the connection to private messages fails.
func (*Application) DisconnectPM ¶
func (app *Application) DisconnectPM()
DisconnectPM disconnects from private messages.
func (*Application) GetContext ¶ added in v0.0.3
func (app *Application) GetContext() context.Context
GetContext returns the context.Context of the application.
Returns:
- context.Context: The context of the application.
func (*Application) Initialize ¶
func (app *Application) Initialize() *Application
Initialize initializes the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) JoinGroup ¶
func (app *Application) JoinGroup(groupName string) error
JoinGroup joins a group in the application.
Args:
- groupName: The name of the group to join.
Returns:
- error: An error if the group cannot be joined.
func (*Application) LeaveGroup ¶
func (app *Application) LeaveGroup(groupName string) error
LeaveGroup leaves a group in the application.
Args:
- groupName: The name of the group to leave.
Returns:
- error: An error if the group cannot be left.
func (*Application) Park ¶
func (app *Application) Park()
Park waits for the application to stop or receive an interrupt signal.
func (*Application) PrivateAPI ¶ added in v0.0.3
func (app *Application) PrivateAPI() *PrivateAPI
PrivateAPI returns the PrivateAPI used in the application.
Returns:
- *PrivateAPI: The private API used in the application.
func (*Application) PublicAPI ¶ added in v0.0.3
func (app *Application) PublicAPI() *PublicAPI
PublicAPI returns the PublicAPI used in the application.
Returns:
- *PublicAPI: The public API used in the application.
func (*Application) RemoveErrorHandler ¶ added in v0.0.3
func (app *Application) RemoveErrorHandler(handler Handler) *Application
RemoveErrorHandler removes an error handler from the application.
Args:
- handler: The error handler to remove from the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) RemoveHandler ¶
func (app *Application) RemoveHandler(handler Handler) *Application
RemoveHandler removes a handler from the application.
Args:
- handler: The handler to remove from the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) Start ¶
func (app *Application) Start(ctx context.Context) *Application
Start starts the application.
Args:
- ctx: The context for running the application.
Returns:
- *Application: The application instance for method chaining.
func (*Application) UsePersistence ¶ added in v0.0.3
func (app *Application) UsePersistence(persistence Persistence) *Application
UsePersistence enables the persistence layer for the application.
Args:
- persistence: The persistence layer to use for the application.
Returns:
- *Application: The application instance for method chaining.
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.
func (*Backoff) Sleep ¶
Sleep is a mock of time.Sleep, that is also responsive to the cancel signal. It adds some jitter to the context and waits until the context is done.
Args:
- ctx: The context used for cancellation.
Returns:
- bool: True if the sleep was cancelled before the deadline, false otherwise.
type BanWord ¶
type BanWord struct { WholeWords string `json:"wholeWords"` // Whole words to be banned. Words string `json:"words"` // Words to be banned. }
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 Blocked ¶
type Blocked struct { IP string // IP address of the blocked user. ModerationID string // Moderation ID of the block. Target string // Target username. Blocker string // Username of the blocker. Time time.Time // Time of blocking. }
Blocked represents a banned user in a group.
type Callback ¶
Callback is a function type that represents a callback function for handling events.
It takes an *Event and a *Context as arguments and performs the desired actions based on the event.
type ChatFilter ¶
type ChatFilter struct {
Chats []string // Chats is a list of chat names to filter events based on chat information.
}
ChatFilter represents a filter for chats.
It filters events based on the name of the chat associated with the event.
func (*ChatFilter) Add ¶
func (f *ChatFilter) Add(chatName string)
Add adds a chat to the filter's list of chats.
Args:
- chatName: The chat name to add to the filter's list.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical AND of the current filter and the provided filter.
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.
Args:
- event: The event to check against the filter conditions.
Returns:
- bool: True if the event's group is in the filter's list of chats, false otherwise.
func (*ChatFilter) Not ¶
func (f *ChatFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
Returns:
- Filter: A new NotFilter representing the logical NOT of 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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical OR of the current filter and the provided filter.
func (*ChatFilter) Remove ¶
func (f *ChatFilter) Remove(chatName string)
Remove removes a chat from the filter's list of chats.
Args:
- chatName: The chat name to remove from the filter's list.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical XOR of the current filter and the provided filter.
type CombineFilter ¶
type CombineFilter struct { Left Filter // Left represents the first filter to be combined. Right Filter // Right represents the second filter to be combined. Mode int // Mode specifies the combination mode: 0 for AND, 1 for OR, and 2 for XOR. }
CombineFilter is a struct that represents the logical combination of two filters.
It supports AND, OR, and XOR operations.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical AND of the current filter and the provided filter.
func (*CombineFilter) Check ¶
func (f *CombineFilter) Check(event *Event) bool
Check returns true if the combination of the left and right filters satisfies the specified mode.
Args:
- event: The event to check against the filter conditions.
Returns:
- bool: True if the event passes the filter conditions, false otherwise.
func (*CombineFilter) Not ¶
func (f *CombineFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
Returns:
- Filter: A new NotFilter representing the logical NOT of 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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical OR of the current filter and the provided filter.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical XOR of the current filter and the provided filter.
type CommandHandler ¶
type CommandHandler struct { Callback Callback // Callback is the function that will be invoked when a command event is triggered. Filter Filter // Filter is the filter that will be applied to the events before invoking the callback. Commands []string // Commands is a list of command names that this handler will respond to. // contains filtered or unexported fields }
CommandHandler is a struct that implements the Handler interface for handling command in message events.
It filters events based on a command prefix and a list of commands, and invokes a callback function when a matching command is found. The handler also supports filtering events using a Filter object.
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.
Args:
- event: The event to check.
Returns:
- bool: True if the event is a command event that matches the prefix and command, false otherwise.
func (*CommandHandler) Invoke ¶
func (ch *CommandHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the command event.
Args:
- event: The event to handle.
- context: The context for the event.
type Config ¶
type Config struct { Username string `json:"username"` // Username of the configuration. Password string `json:"password"` // Password of the configuration. AnonName string `json:"anonname"` // Anonymous name of the configuration. Groups []string `json:"groups"` // List of groups in the configuration. NameColor string `json:"namecolor"` // Name color in the configuration. TextColor string `json:"textcolor"` // Text color in the configuration. TextFont string `json:"textfont"` // Text font in the configuration. TextSize int `json:"textsize"` // Text size in the configuration. SessionID string `json:"sessionid"` // Session ID in the configuration. EnableBG bool `json:"enablebg"` // Enable background in the configuration. EnablePM bool `json:"enablepm"` // Enable private messages in the configuration. Debug bool `json:"debug"` // Debug mode in the configuration. Prefix string `json:"prefix"` // Prefix for commands in the configuration. }
Config represents a configuration object.
func LoadConfig ¶
LoadConfig loads the configuration from the specified file.
The function reads the configuration from the specified file and unmarshals it into a Config struct. It returns a pointer to the Config struct and any error encountered during loading.
Args:
- filename: The name of the configuration file.
Returns:
- *Config: A pointer to the Config struct.
- error: An error if the loading fails.
type Context ¶
type Context struct { App *Application // App is a pointer to the Application that manages this context. ChatData *SyncMap[string, any] // ChatData is a synchronized map to store data specific to the chat. BotData *SyncMap[string, any] // BotData is a synchronized map to store data specific to the bot. }
Context represents the context for event callback.
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 // Check evaluates if the given event passes the filter conditions. And(Filter) Filter // And returns a new filter that combines the current filter with another using logical AND. Or(Filter) Filter // Or returns a new filter that combines the current filter with another using logical OR. Xor(Filter) Filter // Xor returns a new filter that combines the current filter with another using logical XOR. Not() Filter // Not returns a new filter that negates the current filter using logical NOT. }
Filter is an interface that defines the methods for filtering events.
It provides methods for checking if an event passes the filter conditions, combining filters using logical operators (AND, OR, XOR), and negating filters using logical NOT.
func NewChatFilter ¶
NewChatFilter returns a new ChatFilter.
Args:
- groupnames: A list of chat names to filter events based on chat information.
Returns:
- Filter: A new ChatFilter initialized with the provided chat names.
func NewRegexFilter ¶
NewRegexFilter returns a new RegexFilter.
Args:
- pattern: The regular expression pattern to use for filtering messages.
Returns:
- Filter: A new RegexFilter initialized with the provided regular expression pattern.
func NewUserFilter ¶
NewUserFilter returns a new UserFilter.
Args:
- usernames: A list of usernames to filter events based on user information.
Returns:
- Filter: A new UserFilter initialized with the provided usernames.
type FontFamily ¶ added in v0.0.3
type FontFamily int
const ( FontFamilyArial FontFamily = iota FontFamilyComic FontFamilyGeorgia FontFamilyHandwriting FontFamilyImpact FontFamilyPalatino FontFamilyPapyrus FontFamilyTimes FontFamilyTypewriter )
type FullProfile ¶
type FullProfile struct { XMLName xml.Name `xml:"mod"` // Tag name Body QueryEscaped `xml:"body"` // Full profile info T string `xml:"t"` // Reserved }
FullProfile represents a full profile of a user.
type GobPersistence ¶ added in v0.0.3
type GobPersistence 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 }
GobPersistence is responsible for loading and saving data to a gob 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 (*GobPersistence) Close ¶ added in v0.0.3
func (p *GobPersistence) Close() error
Close stops the auto save routine and saves the data to the file.
Returns:
- error: An error if closing fails.
func (*GobPersistence) DelChatData ¶ added in v0.0.3
func (p *GobPersistence) DelChatData(key string)
DelChatData deletes the ChatData for the given key.
Args:
- key: The key to delete the ChatData for.
func (*GobPersistence) GetBotData ¶ added in v0.0.3
func (p *GobPersistence) GetBotData() *SyncMap[string, any]
GetBotData returns a pointer to the BotData.
Returns:
- *SyncMap[string, any]: A pointer to the bot-related data.
func (*GobPersistence) GetChatData ¶ added in v0.0.3
func (p *GobPersistence) 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.
Args:
- key: The key to retrieve the ChatData for.
Returns:
- *SyncMap[string, any]: A pointer to the chat-related data for the given key.
func (*GobPersistence) Initialize ¶ added in v0.0.3
func (p *GobPersistence) Initialize() error
Initialize initializes the GobPersistence struct by loading the data from the file and starting the auto save routine.
Returns:
- error: An error if initialization fails.
func (*GobPersistence) Load ¶ added in v0.0.3
func (p *GobPersistence) Load() error
Load loads the data from the file into the GobPersistence struct.
Args:
- none
Returns:
- error: An error if loading fails.
func (*GobPersistence) Runner ¶ added in v0.0.3
func (p *GobPersistence) Runner(ctx context.Context)
Runner starts a goroutine that manages the persistence layer.
Args:
- ctx: The context for running the auto save operations.
Returns:
- none
func (*GobPersistence) Save ¶ added in v0.0.3
func (p *GobPersistence) Save() error
Save saves the data from the GobPersistence struct to the file.
Returns:
- error: An error if saving fails.
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. UserID int // The user 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 [Group.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.
It provides methods for connecting, disconnecting, sending messages, retrieving user status, and managing settings. The Group struct also handles events related to private messages, friend status, and user profile updates.
func (*Group) AddModerator ¶
AddModerator adds a moderator to the group with the specified username and access level.
Args:
- username: The username of the new moderator.
- access: The access level to assign to the moderator.
Returns:
- error: An error if adding the moderator fails.
func (*Group) BanUser ¶
BanUser bans the user associated with the specified message.
Args:
- message: The message containing the user details to ban.
Returns:
- error: An error if banning the user fails.
func (*Group) ClearAll ¶
ClearAll clears all messages in the group.
Returns:
- error: An error if clearing all messages fails.
func (*Group) Connect ¶
Connect establishes a connection to the server.
Args:
- ctx: The context for the connection.
Returns:
- error: An error if the connection cannot be established.
func (*Group) Delete ¶
Delete deletes the specified message from the group.
Args:
- message: The message to delete.
Returns:
- error: An error if deleting the message fails.
func (*Group) DeleteAll ¶
DeleteAll deletes all messages in the group.
Args:
- message: The message details to match for deletion.
Returns:
- error: An error if deleting all messages fails.
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.
Returns:
- string: The announcement text.
- bool: True if announcements are enabled, otherwise false.
- time.Duration: The interval between announcements.
- error: An error if retrieving the announcement settings fails.
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 next offset can be defined from the last [Blocked.Time]. The returned order is from newer to older.
Args:
- offset: The offset time to start retrieving the ban list.
- amount: The number of banned users to retrieve.
Returns:
- []Blocked: A list of blocked users.
- error: An error if retrieving the ban list fails.
func (*Group) GetBanWords ¶
GetBanWords retrieves the banned word settings for the group.
Returns:
- BanWord: The banned word settings for the group.
- error: An error if retrieving the banned word settings fails.
func (*Group) GetContext ¶
GetContext returns the context.Context of the group chat.
Returns:
- context.Context: The context of the group chat.
func (*Group) GetLastUserMessage ¶
GetLastUserMessage retrieves the last message sent by the specified username in the group.
Note:
- This is useful for banning a user by their username.
Args:
- username: The username to retrieve the last message for.
Returns:
- *Message: The last Message object sent by the specified user.
- bool: A boolean indicating if a message was found.
func (*Group) GetModActions ¶
GetModActions retrieves a list of moderator actions (mod actions) for the group.
Args:
- dir: The direction to retrieve the mod actions, "prev" for later or "next" for earlier actions.
- offset: The ID offset to retrieve mod actions from [ModAction.ID]. Later ID - 1 for "prev" or earlier ID + 1 for "next".
Returns:
- []*ModAction: A list of ModAction objects representing the moderator actions.
- error: An error if retrieving the mod actions fails.
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.
Returns:
- *SyncMap[string, *Participant]: The current participants.
- error: An error if fetching the participants fails.
func (*Group) GetParticipantsStop ¶
GetParticipantsStop stops the participant event feeds.
This will leave [Group.Participants], [Group.UserCount], [Group.AnonCount] out of date.
Returns:
- error: An error if stopping the fetch fails.
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.
Returns:
- int: The premium flag.
- time.Time: The expiration time of the premium status.
- error: An error if retrieving the premium info fails.
func (*Group) GetRateLimit ¶
GetRateLimit retrieves the rate limit settings for the group.
Returns:
- time.Duration: The current rate limit.
- time.Duration: The current rate limit duration.
- error: An error if retrieving the rate limit fails.
func (*Group) GetUnbanList ¶
GetUnbanList retrieves a list of unblocked users (unban list) for the group.
The offset can be set to zero time to retrieve the newest result. The next offset can be defined from the last [Unblocked.Time]. The returned order is from newer to older.
Args:
- offset: The offset time to start retrieving the unban list.
- amount: The number of unbanned users to retrieve.
Returns:
- []Unblocked: A list of unblocked users.
- error: An error if retrieving the unban list fails.
func (*Group) IsRestricted ¶
IsRestricted checks if the group is restricted.
The restriction can originate from either a flood ban or a rate limit.
Returns:
- bool: True if the group is restricted.
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.
Args:
- username: The username to log in with.
- password: The password to log in with. If empty, logs in as an anonymous user.
Returns:
- error: An error if the login fails.
func (*Group) Logout ¶
Logout logs out from the group.
Returns:
- error: An error if the logout fails.
func (*Group) ProfileRefresh ¶
ProfileRefresh notifies the server to refresh the profile.
Returns:
- error: An error if the operation fails.
func (*Group) PropagateEvent ¶
PropagateEvent propagates the WebSocket frame back to the listener goroutine.
It is utilized when the Group.SyncSend callback receives unwanted frames.
Args:
- frame: The WebSocket frame to propagate.
func (*Group) Reconnect ¶
Reconnect reconnects the group to the server.
Returns:
- error: An error if the reconnection fails.
func (*Group) RemoveModerator ¶
RemoveModerator removes the specified moderator from the group.
Args:
- username: The name of the moderator to remove.
Returns:
- error: An error if the removal fails.
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.
Args:
- query: The user name or IP address to search for.
Returns:
- Blocked: The banned user details.
- bool: True if the banned user is found, otherwise false.
- error: An error if searching for the banned user fails.
func (*Group) Send ¶
Send joins the [args] with a ":" separator and then sends it to the server asynchronously.
Note:
- A terminator should be included in the last [args].
- The terminator can be "\r\n" or "\x00" depending on the command.
Args:
- args: The arguments to send to the server.
Returns:
- error: An error if sending the message fails.
func (*Group) SendMessage ¶
SendMessage sends a message to the group with the specified text and optional arguments.
It returns a pointer to the sent *Message and an error (if any occurred). The text can include formatting placeholders (%s, %d, etc.), and optional arguments can be provided to fill in these placeholders. The function also handles flood warnings, restricted messages, spam warnings, rate limiting, and other Chatango-specific events. If the group is logged in, the message text is styled with the group's name color, text size, text color, and text font. If the group is anonymous, the message text is modified with the anonymous seed based on the group's [Group.AnonName] and [Group.UserID]. The function replaces newlines with the "<br/>" HTML tag to format the message properly.
Args:
- text: The message text.
- a: Optional arguments to format the message text.
Returns:
- *Message: The sent message.
- error: An error if sending the message fails.
func (*Group) SendMessageChunked ¶
SendMessageChunked 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.
Args:
- text: The large message text.
- chunkSize: The size of each chunk.
Returns:
- []*Message: The sent messages.
- error: An error if sending the message in chunks fails.
func (*Group) SetAnnouncement ¶
SetAnnouncement sets the announcement settings for the group.
Args:
- annc: The announcement text to set.
- enable: True to enable announcements, false to disable.
- interval: The interval between announcements.
Returns:
- error: An error if setting the announcement fails.
func (*Group) SetBackground ¶
SetBackground sets the background status of the group.
Args:
- enable: True to enable the background feature, false to disable.
Returns:
- error: An error if setting the background fails.
func (*Group) SetBanWords ¶
SetBanWords sets the banned word settings for the group.
Args:
- banWord: The banned word settings to set.
Returns:
- error: An error if setting the banned word settings fails.
func (*Group) SetMedia ¶
SetMedia sets the media status of the group.
Args:
- enable: True to enable the media feature, false to disable.
Returns:
- error: An error if setting the media fails.
func (*Group) SetRateLimit ¶
SetRateLimit sets the rate limit interval for the group.
Args:
- interval: The new rate limit interval.
Returns:
- time.Duration: The set rate limit.
- error: An error if setting the rate limit fails.
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 Group.SyncSendWithTimeout.
Args:
- callback: The function to handle received frames.
- args: The arguments to send.
Returns:
- error: An error if sending the arguments or receiving a response fails.
func (*Group) SyncSendWithTimeout ¶
func (g *Group) SyncSendWithTimeout(callback func(string) bool, timeout time.Duration, args ...string) (err error)
SyncSendWithTimeout sends the specified arguments and waits for a response or timeout.
First, a [Group.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 [false] if a correct frame is acquired, and [true] otherwise.
Args:
- callback: The function to handle received frames.
- timeout: The duration to wait for a response.
- args: The arguments to send.
Returns:
- error: An error if sending the arguments or receiving a response fails.
func (*Group) UnbanAll ¶
UnbanAll unblocks all blocked users.
Returns:
- int: The amount of unblocked users.
- error: An error if unblocking all users fails.
func (*Group) UnbanUser ¶
UnbanUser unblocks the specified blocked user.
Args:
- blocked: The blocked user details to unblock.
Returns:
- error: An error if unblocking the user fails.
func (*Group) UpdateGroupFlag ¶
UpdateGroupFlag updates the group's flag by adding and removing specific flags.
Args:
- addition: The flags to add.
- removal: The flags to remove.
Returns:
- error: An error if updating the group's flag fails.
func (*Group) UpdateModerator ¶
UpdateModerator updates the access level of the specified moderator.
Args:
- username: The name of the moderator to update.
- access: The new access level to set for the moderator.
Returns:
- error: An error if the update fails.
type GroupInfo ¶
GroupInfo represents a group info.
func (*GroupInfo) GetMessage ¶
GetDescription returns the description of the group.
type Handler ¶
type Handler interface { Check(*Event) bool // Check checks if the event satisfies the conditions specified by the handler. Invoke(*Event, *Context) // Invoke handles the event using the specified callback and context. }
Handler is an interface that defines the methods for handling events.
It provides methods for checking if an event satisfies the conditions specified by the handler, and invoking a callback function to handle the event using the specified context.
func NewCommandHandler ¶
NewCommandHandler returns a new CommandHandler.
Args:
- callback: The callback function to invoke when a command event is triggered.
- filter: The filter to apply to the events before invoking the callback.
- commands: A list of command names that this handler will respond to.
Returns:
- Handler: A new CommandHandler instance.
func NewMessageHandler ¶
NewMessageHandler returns a new MessageHandler.
Args:
- callback: The callback function to invoke when a message event is triggered.
- filter: The filter to apply to the events before invoking the callback.
Returns:
- Handler: A new MessageHandler instance.
func NewTypeHandler ¶
NewTypeHandler returns a new TypeHandler.
Args:
- callback: The callback function to invoke when an event of the specified type is triggered.
- filter: The filter to apply to the events before invoking the callback.
- eventType: The type of event that this handler will respond to.
Returns:
- Handler: A new TypeHandler instance.
type KeyValue ¶
KeyValue represents a key-value pair. This is a struct helper for "emod" ModAction parsing.
type Location ¶
type Location struct { Country string `xml:"c,attr"` // Country name or US postal code G string `xml:"g,attr"` // Reserved Latitude float64 `xml:"lat,attr"` // Latitude Longitude float64 `xml:"lon,attr"` // Longitude Text string `xml:",chardata"` // String text of the location }
Location represents the location information of a user.
type Message ¶
type Message struct { Group *Group // Group represents the group chat where the message originated (nil if private chat). Private *Private // Private represents the private chat where the message originated (nil if group chat). IsPrivate bool // IsPrivate indicates whether the message is from a private chat. User *User // User represents the user who sent the message. Text string // Text contains the parsed text of the message. RawText string // RawText contains the raw text of the message. UserID int // UserID is the unique identifier of the user who sent the message. ID string // ID is the unique identifier of the message. ModerationID string // ModerationID is the unique identifier used for moderation actions on the message. UserIP string // UserIP is the IP address of the user who sent the message. Time time.Time // Time represents the time when the message was sent. ReceivedTime time.Time // ReceivedTime represents the time when the message was received. Flag MessageChannel // Flag represents the flag value associated with the message. FromSelf bool // FromSelf indicates whether the message was sent by the current user. FromAnon bool // FromAnon indicates whether the message was sent by an anonymous user. AnonSeed int // AnonSeed represents the seed value used for anonymous user identification. }
Message represents a message that comes from a group or private chat.
It provides methods for replying to the message, deleting the message, deleting all messages from the sender, banning the user who sent the message, and accessing various properties of the message. The message object also contains information about the sender, the content, the time of sending, and the channel flags.
func ParseAnnouncement ¶
ParseAnnouncement parses a group announcement data.
It extracts the announcement text from the provided data.
Args:
- data: The group announcement data.
- group: The group chat where the announcement originated.
Returns:
- *Message: A pointer to the parsed Message object.
func ParseGroupMessage ¶
ParseGroupMessage parses a group message data.
It extracts information about the sender, the content, the time of sending, and the channel flags from the provided data.
Args:
- data: The group message data.
- group: The group chat where the message originated.
Returns:
- *Message: A pointer to the parsed Message object.
func ParsePrivateMessage ¶
ParsePrivateMessage parses a private message data.
It extracts information about the sender, the content, the time of sending, and the channel flags from the provided data.
Args:
- data: The private message data.
- private: The private chat where the message originated.
Returns:
- *Message: A pointer to the parsed Message object.
func (*Message) BanUser ¶
BanUser bans the user who sent the current message from the group.
If the message is from a group, it calls the [BanUser] method on the associated Group to perform the banning action. If the message is private, this method does nothing and returns nil.
Returns:
- error: An error if any occurs during the banning process.
func (*Message) Channel ¶
func (m *Message) Channel() (c MessageChannel)
Channel returns the channel flag of the message.
It combines the individual channel flags (e.g., FlagRedChannel, FlagOrangeChannel, etc.) into a single MessageChannel value.
Returns:
- MessageChannel: The combined channel flag value.
func (*Message) Delete ¶
Delete deletes the message.
If the message is from a group, it calls the [Delete] method on the associated Group to remove the message from the group chat. If the message is private, this method does nothing and returns nil.
Returns:
- error: An error if any occurs during the deletion process.
func (*Message) DeleteAll ¶
DeleteAll deletes all messages from the sender of the current message.
If the message is from a group, it calls the [DeleteAll] method on the associated Group to remove all messages from the sender in the group chat. If the message is private, this method does nothing and returns nil.
Returns:
- error: An error if any occurs during the deletion process.
func (*Message) HasBackground ¶
HasBackground checks if the message has background flag.
Returns:
- bool: True if the message has the background flag, otherwise false.
func (*Message) HasMedia ¶
HasMedia checks if the message has media flag.
Returns:
- bool: True if the message has the media flag, otherwise false.
func (*Message) HasModIcon ¶ added in v0.0.3
HasModIcon checks if the message has mod icon flag.
Returns:
- bool: True if the message has the mod icon flag, otherwise false.
func (*Message) HasPremium ¶
HasPremium checks if the message has premium flag.
Returns:
- bool: True if the message has the premium flag, otherwise false.
func (*Message) HasStaffIcon ¶ added in v0.0.3
HasStaffIcon checks if the message has staff icon flag.
Returns:
- bool: True if the message has the staff icon flag, otherwise false.
func (*Message) IsCensored ¶ added in v0.0.2
IsCensored checks if the message contains censor.
Returns:
- bool: True if the message is censored, otherwise false.
func (*Message) IsInModChannel ¶ added in v0.0.3
IsInModChannel checks if the message is in a mod channel.
Returns:
- bool: True if the message is in a mod channel, otherwise false.
func (*Message) NameColor ¶
NameColor returns the name color of the message.
It extracts the name color from the raw text of the message.
Returns:
- string: The name color of the message.
func (*Message) Reply ¶
Reply sends a reply to the message with the specified text.
If the message is from a group, it calls the [SendMessage] method on the associated Group to send the reply. If the message is private, it calls the [SendMessage] method on the associated Private to send the reply to the user. The text can include formatting placeholders (%s, %d, etc.), and optional arguments can be provided to fill in these placeholders.
Args:
- text: The text of the reply message.
- a: Optional arguments to fill in placeholders in the message text.
Returns:
- *Message: A pointer to the sent message (nil if the message is private).
- error: An error if any occurs during the message sending process.
type MessageBackground ¶ added in v0.0.2
type MessageBackground struct { Align string `xml:"align,attr"` // Background image alignment Alpha int `xml:"bgalp,attr"` // Background color transparency Color string `xml:"bgc,attr"` // Background color HasRecording int64 `xml:"hasrec,attr"` // Media recording timestamp (ms) ImageAlpha int `xml:"ialp,attr"` // Background image transparency IsVid bool `xml:"isvid,attr"` // Is the Media a video? Tile bool `xml:"tile,attr"` // Tile image? UseImage bool `xml:"useimg,attr"` // Use image? // contains filtered or unexported fields }
MessageBackground represents the message background information of a user.
func (*MessageBackground) GetForm ¶ added in v0.0.2
func (mb *MessageBackground) GetForm() url.Values
GetForm returns the URL-encoded form values for the `MessageBackground`.
func (*MessageBackground) GetImageURL ¶ added in v0.0.3
func (mb *MessageBackground) GetImageURL() string
type MessageChannel ¶ added in v0.0.3
type MessageChannel int64
const ( FlagPremium MessageChannel FlagBackground FlagMedia FlagCensored FlagModIcon FlagStaffIcon FlagRedChannel // js: #ed1c24 FlagOrangeChannel // js: #ee7f22 FlagGreenChannel // js: #39b54a FlagBlueChannel // js: #25aae1 FlagAzureChannel // js: #0e76bc FlagPurpleChannel // js: #662d91 FlagPinkChannel // js: #ed217c FlagModChannel )
type MessageHandler ¶
type MessageHandler struct { Callback Callback // Callback is the function that will be invoked when a message event is triggered. Filter Filter // Filter is the filter that will be applied to the events before invoking the callback. }
MessageHandler is a struct that implements the Handler interface for handling message events.
It filters events based on a Filter object and invokes a callback function when a matching message event is found.
func (*MessageHandler) Check ¶
func (mh *MessageHandler) Check(event *Event) bool
Check checks if the event is a message event.
Args:
- event: The event to check.
Returns:
- bool: True if the event is a message event, false otherwise.
func (*MessageHandler) Invoke ¶
func (mh *MessageHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the message event.
Args:
- event: The event to handle.
- context: The context for the event.
type MessageStyle ¶ added in v0.0.2
type MessageStyle struct { FontFamily string `json:"fontFamily"` // The font family used for the message text. FontSize string `json:"fontSize"` // The font size used for the message text. Bold bool `json:"bold"` // A boolean value indicating whether the message text should be displayed in bold. StylesOn bool `json:"stylesOn"` // A boolean value indicating whether the message styles are enabled. UseBackground string `json:"usebackground"` // The background color used for the message text. Italics bool `json:"italics"` // A boolean value indicating whether the message text should be displayed in italics. TextColor string `json:"textColor"` // The color used for the message text. Underline bool `json:"underline"` // A boolean value indicating whether the message text should be underlined. NameColor string `json:"nameColor"` // The color used for the username or sender's name in the message. }
MessageStyle represents the style settings for a message.
func (MessageStyle) GetForm ¶ added in v0.0.2
func (mb MessageStyle) GetForm() url.Values
GetForm returns the URL-encoded form values for the `MessageStyle`.
type MiniProfile ¶
type MiniProfile struct { XMLName xml.Name `xml:"mod"` // Tag name Body QueryEscaped `xml:"body"` // Mini profile info Gender string `xml:"s"` // Gender (M, F) Birth BirthDate `xml:"b"` // Date of birth (yyyy-mm-dd) Location Location `xml:"l"` // Location Premium PremiumDate `xml:"d"` // Premium expiration // contains filtered or unexported fields }
MiniProfile represents a mini profile of a user.
func (MiniProfile) PhotoLargeURL ¶ added in v0.0.3
func (m MiniProfile) PhotoLargeURL() string
type ModAction ¶
type ModAction struct { ID int // ID is the unique identifier of the moderation action. Type string // Type is the type of the moderation action, e.g., "emod", "brdc", "cinm", "chan", "cntr", etc. User string // User is the name of the moderator who performed the action. IP string // IP is the IP address of the moderator who performed the action. Target string // Target is the name of the user that the action was performed on. Time time.Time // Time is the timestamp when the action was performed. Extra string // Extra is any additional information or context related to the moderation action. }
ModAction represents a moderation action.
func ParseModActions ¶
ParseModActions parses a string data and returns a slice of ModAction objects
Args:
- data: The string containing semicolon-separated entries of mod actions.
Returns:
- []*ModAction: A slice of pointers to the parsed ModAction objects.
func (*ModAction) ExtraAsBool ¶
ExtraAsBool returns the Extra field as a boolean.
Returns:
- bool: The parsed boolean value.
func (*ModAction) ExtraAsInt ¶
ExtraAsInt returns the Extra field as an int64.
Returns:
- int64: The parsed int64 value.
func (*ModAction) ExtraAsSliceInt ¶
ExtraAsSliceInt returns the Extra field as a slice of int64.
Returns:
- []int64: The parsed slice of int64 values.
func (*ModAction) ExtraAsSliceInterface ¶
func (ma *ModAction) ExtraAsSliceInterface() (ret []interface{})
ExtraAsSliceInterface returns the Extra field as a slice of interface{}.
Returns:
- []interface{}: The parsed slice of interface{} values.
func (*ModAction) ExtraBanWord ¶
ExtraBanWord returns the Extra field as a BanWord.
Returns:
- BanWord: The parsed BanWord object.
func (*ModAction) ExtraDescription ¶
ExtraDescription returns the Extra field as a GroupInfo.
Returns:
- GroupInfo: The parsed GroupInfo object.
type NotFilter ¶
type NotFilter struct {
Base Filter // Base represents the filter to be negated.
}
NotFilter is a struct that represents the logical NOT of a filter.
It negates the result of the base filter.
func (*NotFilter) And ¶
And returns a new CombineFilter that combines the current filter with the provided filter using logical AND.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical AND of the current filter and the provided filter.
func (*NotFilter) Check ¶
Check returns the logical negation of the base filter's result.
Args:
- event: The event to check against the filter conditions.
Returns:
- bool: True if the event does not pass the base filter conditions, false otherwise.
func (*NotFilter) Not ¶
Not returns a new NotFilter negating the current filter.
Returns:
- Filter: A new NotFilter representing the logical NOT of the current filter.
func (*NotFilter) Or ¶
Or returns a new CombineFilter that combines the current filter with the provided filter using logical OR.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical OR of the current filter and the provided filter.
func (*NotFilter) Xor ¶
Xor returns a new CombineFilter that combines the current filter with the provided filter using logical XOR.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical XOR of the current filter and the provided filter.
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.
It provides thread-safe methods for setting, getting, deleting, and iterating over key-value pairs in the order they were added. The map also supports Gob encoding and decoding for persistence.
func NewOrderedSyncMap ¶
func NewOrderedSyncMap[K comparable, V any]() OrderedSyncMap[K, V]
NewOrderedSyncMap creates a new instance of OrderedSyncMap.
Returns:
- OrderedSyncMap[K, V]: 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.
Args:
- key: The key to remove.
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.
Args:
- key: The key to retrieve the value for.
Returns:
- V: The value associated with the key.
- bool: True if the key exists in the map, false otherwise.
func (*OrderedSyncMap[K, V]) GobDecode ¶
func (sm *OrderedSyncMap[K, V]) GobDecode(data []byte) error
GobDecode decodes the OrderedSyncMap using Gob.
Args:
- data: The encoded byte slice to decode.
Returns:
- error: An error if decoding fails.
func (*OrderedSyncMap[K, V]) GobEncode ¶
func (sm *OrderedSyncMap[K, V]) GobEncode() ([]byte, error)
GobEncode encodes the OrderedSyncMap using Gob.
Returns:
- []byte: The encoded byte slice.
- error: An error if encoding fails.
func (*OrderedSyncMap[K, V]) Keys ¶
func (sm *OrderedSyncMap[K, V]) Keys() []K
Keys returns a slice of keys in the OrderedSyncMap.
Returns:
- []K: A slice containing all the keys in the map.
func (*OrderedSyncMap[K, V]) Len ¶
func (sm *OrderedSyncMap[K, V]) Len() int
Len returns the number of key-value pairs in the OrderedSyncMap.
Returns:
- int: The number of key-value pairs in the map.
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.
Args:
- fun: The function to call for each key-value pair.
The function takes two arguments:
- key: The key of the current key-value pair.
- value: The value of the current key-value pair.
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.
Args:
- fun: The function to call for each key-value pair.
The function takes two arguments:
- key: The key of the current key-value pair.
- value: The value of the current key-value pair.
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.
Args:
- key: The key to add or update.
- val: The value to associate with the key.
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.
Args:
- key: The key to add or update.
- val: The value to associate with the key.
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.
Args:
- length: The desired length of the map after trimming.
It modifies the OrderedSyncMap in place, removing elements from the beginning of the map until the desired length is reached.
type Participant ¶
type Participant struct { ParticipantID string // Participant ID. UserID int // User ID. User *User // User object. Time time.Time // Time of participation. }
Participant represents a group participant object.
type PeopleQuery ¶
type PeopleQuery struct { AgeFrom int // Minimum age AgeTo int // Maximum age Gender string // Gender (B: both, M: male, F: female, N: unset) 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() 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 PeopleResult ¶ added in v0.0.3
type Persistence ¶
type Persistence interface { Initialize() error // Initialize initializes the persistence layer. Runner(context.Context) // Runner starts a goroutine that manages the persistence layer. Close() error // Close closes the persistence layer and saves any pending data. GetBotData() *SyncMap[string, any] // GetBotData returns a pointer to the bot-related data. GetChatData(string) *SyncMap[string, any] // GetChatData returns a pointer to the chat-related data for the given key. DelChatData(string) // DelChatData deletes the chat-related data for the given key. }
Persistence is an interface that defines the methods for managing data persistence.
It provides methods for initializing, running, closing, and accessing data stored in the persistence layer.
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.
It provides methods for connecting, disconnecting, sending messages, retrieving user status, and managing settings. The Private struct also handles events related to private messages, friend status, and user profile updates.
func (*Private) AddFriend ¶
func (p *Private) AddFriend(username string) (status UserStatus, err error)
AddFriend adds a username to the friend list.
Args:
- username: The username to add.
Returns:
- UserStatus: The status of the added friend.
- error: An error if the operation fails.
func (*Private) Block ¶
Block blocks the user with the specified username.
Args:
- username: The username to block.
Returns:
- error: An error if the operation fails.
func (*Private) Connect ¶
Connect establishes a connection to the server.
Args:
- ctx: The context for the connection.
Returns:
- error: 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.
Args:
- username: The username to connect with.
Returns:
- UserStatus: The status of the connected user.
- error: An error if the operation fails.
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.
Args:
- username: The username to disconnect from.
Returns:
- error: An error if the operation fails.
func (*Private) GetBlocked ¶
GetBlocked retrieves the list of blocked users.
Returns:
- users: A slice of blocked users.
- error: An error if the operation fails.
func (*Private) GetContext ¶
GetContext returns the context.Context of the private chat.
Returns:
- context.Context: 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.
Returns:
- []UserStatus: The list of friends and their status.
- error: An error if the operation fails.
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.
Args:
- usernames: A slice of usernames to retrieve the status for.
Returns:
- []UserStatus: A slice of `UserStatus` objects representing the status of each username.
- error: An error if the operation fails.
func (*Private) GetSettings ¶
func (p *Private) GetSettings() (setting PrivateSetting, err error)
GetSettings retrieves the current settings.
Returns:
- PrivateSetting: The current settings.
- error: An error if the operation fails.
func (*Private) ProfileRefresh ¶
ProfileRefresh notifies the server to refresh the profile.
Returns:
- error: An error if the operation fails.
func (*Private) PropagateEvent ¶
PropagateEvent propagates the WebSocket frame back to the listener goroutine.
It is utilized when the Private.SyncSend callback receives unwanted frames.
Args:
- frame: The WebSocket frame to propagate.
func (*Private) Reconnect ¶
Reconnect attempts to reconnect to the PM server.
Returns:
- error: An error if the reconnection fails.
func (*Private) RemoveFriend ¶
RemoveFriend removes the username from the friend list.
Args:
- username: The username to remove.
Returns:
- error: An error if the operation fails.
func (*Private) Send ¶
Send will join the [args] with a ":" separator and then send it to the server asynchronously.
Note:
- A terminator should be included in the last [args].
- The terminator can be "\r\n" or "\x00" depending on the command.
Args:
- args: The arguments to send to the server.
Returns:
- error: An error if the sending fails.
func (*Private) SendMessage ¶
SendMessage sends a private message to the specified username with the given text and optional arguments.
It returns an error if any occurs during the message sending process. The text can include formatting placeholders (%s, %d, etc.), and optional arguments can be provided to fill in these placeholders. The function also handles a flood warning, a flood ban, and the maximum number of unread messages (51) has been reached. The function replaces newlines with the `<br/>` HTML tag to format the message properly.
Args:
- username: The username to send the message to.
- text: The message text.
- a: Optional arguments to fill in placeholders in the message text.
Returns:
- error: An error if any occurs during the message sending process.\
func (*Private) SetSettings ¶
func (p *Private) SetSettings(setting PrivateSetting) (err error)
SetSettings updates the settings with the provided values.
Args:
- setting: The new settings to apply.
Returns:
- error: An error if the operation fails.
func (*Private) SyncSend ¶
SyncSend will send the [args] and wait until receiving the correct reply or until timeout (default to 5 seconds).
Args:
- cb: The function to call for each received frame.
- args: The arguments to send to the server.
Returns:
- error: An error if the operation fails.
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.
Args:
- callback: The function to call for each received frame.
- timeout: The timeout duration for the operation.
- args: The arguments to send to the server.
Returns:
- error: An error if the operation fails.
func (*Private) Track ¶
func (p *Private) Track(username string) (status UserStatus, err error)
Track retrieves the online status of the username.
Args:
- username: The username to track.
Returns:
- UserStatus: The online status of the username.
- error: An error if the operation fails.
func (*Private) Unblock ¶
Unblock unblocks the user with the specified username.
Args:
- username: The username to unblock.
Returns:
- error: An error if the operation fails.
func (*Private) WentActive ¶
WentActive notifies the server that the user went active.
Returns:
- error: An error if the operation fails.
type PrivateAPI ¶ added in v0.0.3
type PrivateAPI struct { APIClient MessageBackground MessageBackground MessageStyle MessageStyle // contains filtered or unexported fields }
PrivateAPI represents a compilation of various Chatango APIs that needs to be authenticated.
func NewPrivateAPI ¶ added in v0.0.3
func NewPrivateAPI(username, password string, ctx context.Context) *PrivateAPI
NewPrivateAPI creates a new chadango.PrivateAPI instance.
Args:
- username: The username of the Chatango account.
- password: The password of the Chatango account.
- ctx: The context for the API client.
Returns:
- *PrivateAPI: A new PrivateAPI instance.
func (*PrivateAPI) GetCookie ¶ added in v0.0.3
func (p *PrivateAPI) GetCookie(name string) (string, bool)
GetCookie retrieves a cookie value.
Args:
- name: The name of the cookie.
Returns:
- string: The value of the cookie.
- bool: True if the cookie exists, false otherwise.
func (*PrivateAPI) GetCreatedGroups ¶ added in v0.0.3
func (p *PrivateAPI) GetCreatedGroups() map[string]string
GetCreatedGroups returns the map of created chat groups.
Returns:
- map[string]string: A map of created groups, where the key is the group name and the value is the group description.
func (*PrivateAPI) GetGCMID ¶ added in v0.0.3
func (p *PrivateAPI) GetGCMID() string
GetGCMID returns the GCM ID of the user.
Returns:
- string: The GCM ID of the user.
func (*PrivateAPI) GetGCMToken ¶ added in v0.0.3
func (p *PrivateAPI) GetGCMToken() string
GetGCMToken returns the GCM token of the user.
Returns:
- string: The GCM token of the user.
func (*PrivateAPI) GetMsgBgImage ¶ added in v0.0.3
func (p *PrivateAPI) GetMsgBgImage() string
GetMsgBgImage returns the URL of the message background image.
Returns:
- string: The URL of the message background image.
func (*PrivateAPI) GetRecentGroups ¶ added in v0.0.3
func (p *PrivateAPI) GetRecentGroups() map[string]string
GetRecentGroups returns the map of recent chat groups.
Returns:
- map[string]string: A map of recent groups, where the key is the group name and the value is the group description.
func (*PrivateAPI) GetUnreadMsgCount ¶ added in v0.0.3
func (p *PrivateAPI) GetUnreadMsgCount() int
GetUnreadMsgCount returns the number of unread private messages.
Returns:
- int: The number of unread private messages.
func (*PrivateAPI) IsLoggedIn ¶ added in v0.0.3
func (p *PrivateAPI) IsLoggedIn() bool
IsLoggedIn returns true if the user is logged in, false otherwise.
Returns:
- bool: True if the user is logged in, false otherwise.
func (*PrivateAPI) Login ¶ added in v0.0.3
func (p *PrivateAPI) Login() error
Login authenticates the client by obtaining and storing the necessary cookies.
Returns:
- error: An error if the login fails.
func (*PrivateAPI) RegisterGCM ¶ added in v0.0.3
func (p *PrivateAPI) RegisterGCM() (err error)
RegisterGCM registers the GCM ID with the provided token.
Returns:
- error: An error if the registration fails.
func (*PrivateAPI) RetrieveMsgBg ¶ added in v0.0.3
func (p *PrivateAPI) RetrieveMsgBg() error
RetrieveMsgBg retrieves the message background of the current user.
Returns:
- error: An error if the retrieval fails.
func (*PrivateAPI) RetrieveMsgStyle ¶ added in v0.0.3
func (p *PrivateAPI) RetrieveMsgStyle() error
RetrieveMsgStyle retrieves the message style of the current user.
Returns:
- error: An error if the retrieval fails.
func (*PrivateAPI) RetrieveTokenGCM ¶ added in v0.0.3
func (p *PrivateAPI) RetrieveTokenGCM() (err error)
RetrieveTokenGCM retrieves the GCM token for the specified GCM ID.
Returns:
- error: An error if the retrieval fails.
func (*PrivateAPI) RetrieveUpdate ¶ added in v0.0.3
func (p *PrivateAPI) RetrieveUpdate() (err error)
RetrieveUpdate retrieves the latest updates for the user's groups and unread messages.
Returns:
- error: An error if the retrieval fails.
func (*PrivateAPI) SearchPeople ¶ added in v0.0.3
func (p *PrivateAPI) SearchPeople(query PeopleQuery) (result []PeopleResult, err error)
SearchPeople searches for people based on the provided query.
Args:
- query: The search query.
Returns:
- []PeopleResult: A list of search results.
- error: An error if the search fails.
func (*PrivateAPI) SetGCMID ¶ added in v0.0.3
func (p *PrivateAPI) SetGCMID(gcmID string)
SetGCMID sets the GCM ID of the user.
Args:
- gcmID: The GCM ID of the user.
func (*PrivateAPI) SetGCMToken ¶ added in v0.0.3
func (p *PrivateAPI) SetGCMToken(token string)
SetGCMToken sets the GCM token of the user.
Args:
- token: The GCM token of the user.
func (*PrivateAPI) UnregisterGCM ¶ added in v0.0.3
func (p *PrivateAPI) UnregisterGCM() (err error)
UnregisterGCM unregisters the specified GCM ID.
Returns:
- error: An error if the unregistration fails.
func (*PrivateAPI) UpdateMsgBg ¶ added in v0.0.3
func (p *PrivateAPI) UpdateMsgBg() (err error)
UpdateMsgBg updates the message background of the current user.
Returns:
- error: An error if the update fails.
func (*PrivateAPI) UpdateMsgStyle ¶ added in v0.0.3
func (p *PrivateAPI) UpdateMsgStyle() (err error)
UpdateMsgStyle updates the message style of the current user.
Returns:
- error: An error if the update fails.
func (*PrivateAPI) UploadImage ¶ added in v0.0.3
func (p *PrivateAPI) UploadImage(filename string, image io.Reader) (img UploadedImage, err error)
UploadImage uploads an image to the Chatango server.
Args:
- filename: The name of the image file.
- image: The image data.
Returns:
- UploadedImage: The uploaded image information.
- error: An error if the upload fails.
func (*PrivateAPI) UploadMsgBgImage ¶ added in v0.0.3
func (p *PrivateAPI) UploadMsgBgImage(filename string, image io.Reader) (err error)
UploadMsgBgImage uploads an image to be used as the message background.
Args:
- filename: The name of the image file.
- image: The image data.
Returns:
- error: An error if the upload fails.
type PrivateSetting ¶
type PrivateSetting struct { DisableIdleTime bool // Disable idle time in private messages. AllowAnon bool // Allow anonymous messages. EmailOfflineMsg bool // Email offline messages. }
PrivateSetting represents the private message settings.
type PublicAPI ¶ added in v0.0.3
type PublicAPI struct {
APIClient
}
PublicAPI represents a compilation of various Chatango APIs that doesn't needs to be authenticated.
func NewPublicAPI ¶ added in v0.0.3
NewPublicAPI creates a new PublicAPI instance.
Args:
- ctx: The context for the API client.
Returns:
- *PublicAPI: A new instance of PublicAPI.
func (*PublicAPI) CheckUsername ¶ added in v0.0.3
CheckUsername checks whether the specified username is available for purchase.
Args:
- username: The username to check for availability.
Returns:
- bool: `true` if the username is purchasable, `false` otherwise.
- []string: A list of reasons why the username is not available.
- error: An error if the check fails.
func (*PublicAPI) GetBackground ¶ added in v0.0.3
func (p *PublicAPI) GetBackground(username string) (background MessageBackground, err error)
GetBackground retrieves the message background of the specified username.
Args:
- username: The username to retrieve the background for.
Returns:
- MessageBackground: The message background of the specified username.
- error: An error if the retrieval fails.
func (*PublicAPI) GetFullProfile ¶ added in v0.0.3
func (p *PublicAPI) GetFullProfile(username string) (profile FullProfile, err error)
GetFullProfile retrieves the full profile of the specified username.
Args:
- username: The username to retrieve the full profile for.
Returns:
- FullProfile: The full profile of the specified username.
- error: An error if the retrieval fails.
func (*PublicAPI) GetMiniProfile ¶ added in v0.0.3
func (p *PublicAPI) GetMiniProfile(username string) (profile MiniProfile, err error)
GetMiniProfile retrieves the mini profile of the specified username.
Args:
- username: The username to retrieve the mini profile for.
Returns:
- MiniProfile: The mini profile of the specified username.
- error: An error if the retrieval fails.
func (*PublicAPI) GetStyle ¶ added in v0.0.3
func (p *PublicAPI) GetStyle(username string) (style MessageStyle, err error)
GetStyle retrieves the message style of the specified username.
Args:
- username: The username to retrieve the message style for.
Returns:
- MessageStyle: The message style of the specified username.
- error: An error if the retrieval fails.
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 ¶
type RegexFilter struct {
Pattern *regexp.Regexp // Pattern represents the regular expression pattern used for filtering messages.
}
RegexFilter represents a Message filter based on a regular expression pattern.
It filters messages based on whether their text matches the specified 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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical AND of the current filter and the provided filter.
func (*RegexFilter) Check ¶
func (f *RegexFilter) Check(event *Event) bool
Check checks if the event matches the regular expression pattern.
Args:
- event: The event to check against the filter conditions.
Returns:
- bool: True if the event's message text matches the regular expression pattern, false otherwise.
func (*RegexFilter) Not ¶
func (f *RegexFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
Returns:
- Filter: A new NotFilter representing the logical NOT of 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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical OR of the current filter and the provided filter.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical XOR of the current filter and the provided filter.
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.
It provides thread-safe methods for setting, getting, deleting, and iterating over key-value pairs. The map also supports Gob encoding and decoding for persistence.
func NewSyncMap ¶
func NewSyncMap[K comparable, V any]() SyncMap[K, V]
NewSyncMap creates a new instance of SyncMap.
Returns:
- SyncMap[K, V]: 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.
Args:
- key: The key to remove.
func (*SyncMap[K, V]) Get ¶
Get retrieves the value associated with the specified key from the SyncMap.
Args:
- key: The key to retrieve the value for.
Returns:
- V: The value associated with the key.
- bool: True if the key exists in the map, false otherwise.
func (*SyncMap[K, V]) GobDecode ¶
GobDecode decodes the SyncMap using Gob decoding.
Args:
- data: The encoded byte slice to decode.
Returns:
- error: An error if decoding fails.
func (*SyncMap[K, V]) GobEncode ¶
GobEncode encodes the SyncMap using Gob encoding.
Returns:
- []byte: The encoded byte slice.
- error: An error if encoding fails.
func (*SyncMap[K, V]) Keys ¶
func (sm *SyncMap[K, V]) Keys() (keys []K)
Keys returns a slice of keys in the SyncMap.
Returns:
- []K: A slice containing all the keys in the map.
func (*SyncMap[K, V]) Len ¶
Len returns the number of key-value pairs in the SyncMap.
Returns:
- int: The number of key-value pairs in the map.
func (*SyncMap[K, V]) Range ¶
Range iterates over each key-value pair in the SyncMap and calls the specified function.
Args:
- fun: The function to call for each key-value pair.
The function takes two arguments:
- key: The key of the current key-value pair.
- value: The value of the current key-value pair.
If the function returns false, the iteration stops.
type Transport ¶
type Transport struct { Transport http.RoundTripper // Underlying RoundTripper. Headers map[string]string // Custom headers to be added to the requests. }
Transport is a custom RoundTripper implementation. It adds custom headers to the request before performing the request using the underlying Transport.
type TypeHandler ¶
type TypeHandler struct { Callback Callback // Callback is the function that will be invoked when an event of the specified type is triggered. Filter Filter // Filter is the filter that will be applied to the events before invoking the callback. Type EventType // Type is the type of event that this handler will respond to. }
TypeHandler is a struct that implements the Handler interface for handling events of a specific type.
It filters events based on a specific event type and a Filter object, and invokes a callback function when a matching event is found.
func (*TypeHandler) Check ¶
func (th *TypeHandler) Check(event *Event) bool
Check checks if the event is of the specified type.
Args:
- event: The event to check.
Returns:
- bool: True if the event is of the specified type, false otherwise.
func (*TypeHandler) Invoke ¶
func (th *TypeHandler) Invoke(event *Event, context *Context)
Invoke executes the callback function for the event of the specified type.
Args:
- event: The event to handle.
- context: The context for the event.
type Unblocked ¶
type Unblocked struct { IP string // IP address of the unblocked user. ModerationID string // Moderation ID of the unblock. Target string // Target username. Unblocker string // Username of the unblocker. Time time.Time // Time of unblocking. }
Unblocked represents an unblocked user in a group.
type UploadedImage ¶ added in v0.0.3
func (UploadedImage) LargeURL ¶ added in v0.0.3
func (i UploadedImage) LargeURL() string
func (UploadedImage) MessageEmbed ¶ added in v0.0.3
func (i UploadedImage) MessageEmbed() string
func (UploadedImage) ThumbURL ¶ added in v0.0.3
func (i UploadedImage) ThumbURL() string
type User ¶
type User struct { Name string // Name of the user. IsSelf bool // Indicates if the user is self. IsAnon bool // Indicates if the user is anonymous. }
User represents a user object.
type UserFilter ¶
type UserFilter struct {
Users []string // Users is a list of usernames to filter events based on user information.
}
UserFilter represents a filter for users.
It filters events based on the username of the user associated with the event.
func (*UserFilter) Add ¶
func (f *UserFilter) Add(userName string)
Add adds a user to the filter's list of users.
Args:
- userName: The username to add to the filter's list.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical AND of the current filter and the provided filter.
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.
Args:
- event: The event to check against the filter conditions.
Returns:
- bool: True if the event's user is in the filter's list of users, false otherwise.
func (*UserFilter) Not ¶
func (f *UserFilter) Not() Filter
Not returns a new NotFilter negating the current filter.
Returns:
- Filter: A new NotFilter representing the logical NOT of 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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical OR of the current filter and the provided filter.
func (*UserFilter) Remove ¶
func (f *UserFilter) Remove(userName string)
Remove removes a user from the filter's list of users.
Args:
- userName: The username to remove from the filter's list.
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.
Args:
- filter: The filter to combine with the current filter.
Returns:
- Filter: A new CombineFilter representing the logical XOR of the current filter and the provided filter.
type UserStatus ¶
type UserStatus struct { User *User // User object. Time time.Time // Time of the status. Info string // Additional information about the status. Idle time.Duration // Idle duration of the user. }
UserStatus represents the online status of a user.
type WebSocket ¶
type WebSocket struct { Connected bool // Connected indicates whether the WebSocket connection is currently active. Events chan string // Events is a channel for receiving WebSocket events and messages. OnError func(error) // OnError is a callback function that will be called in case of an error during WebSocket operation. // 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.
func (*WebSocket) Connect ¶
Connect establishes a WebSocket connection to the specified URL.
Args:
- url: The WebSocket server URL.
Returns:
- error: An error if the connection fails.
func (*WebSocket) Recv ¶
Recv receives a message from the WebSocket connection.
Returns:
- string: The received message.
- error: An error if the receiving fails.