bot

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2024 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MsgBroadcastStarted defines text to be sent by the bot when the broadcast started
	MsgBroadcastStarted = "Вещание началось. Приобщиться можно тут: https://stream.radio-t.com/"

	// MsgBroadcastFinished defines text to be sent by the bot when the broadcast finished
	MsgBroadcastFinished = "Вещание завершилось"
)
View Source
const Day = 24 * time.Hour

Day is one day duration

Variables

This section is empty.

Functions

func DisplayName added in v0.3.0

func DisplayName(msg Message) string

DisplayName returns user's display name or username or id

func EscapeMarkDownV1Text added in v0.3.0

func EscapeMarkDownV1Text(text string) string

EscapeMarkDownV1Text escapes markdownV1 special characters, used in places where we want to send text as-is. For example, telegram username with underscores would be italicized if we don't escape it. https://core.telegram.org/bots/api#markdown-style

func GenHelpMsg added in v0.3.0

func GenHelpMsg(com []string, msg string) string

GenHelpMsg construct help message from bot's ReactOn

func HumanizeDuration added in v0.3.0

func HumanizeDuration(d time.Duration) string

HumanizeDuration converts time.Duration to readable format

Types

type Anecdote

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

Anecdote bot, returns from jokesrv.fermyon.app or chucknorris.io

func NewAnecdote

func NewAnecdote(client HTTPClient) *Anecdote

NewAnecdote makes a bot for jokesrv.fermyon.app and chucknorris.io

func (Anecdote) Help

func (a Anecdote) Help() string

Help returns help message

func (Anecdote) OnMessage

func (a Anecdote) OnMessage(msg Message) (response Response)

OnMessage returns one entry

func (Anecdote) ReactOn

func (a Anecdote) ReactOn() []string

ReactOn keys

type Banhammer added in v0.3.0

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

Banhammer bot, allows (superusers only) to ban or unban anyone

func NewBanhammer added in v0.3.0

func NewBanhammer(tgClient TgBanClient, superUser SuperUser, maxRecentUsers int) *Banhammer

NewBanhammer makes a bot for admins reacting on ban!user unban!user

func (*Banhammer) Help added in v0.3.0

func (b *Banhammer) Help() string

Help returns help message

func (*Banhammer) OnMessage added in v0.3.0

func (b *Banhammer) OnMessage(msg Message) (response Response)

OnMessage pass msg to all bots and collects responses In order to translate username to ID (mandatory for tg kick/unban) collect up to maxRecentUsers recently seen users

func (*Banhammer) ReactOn added in v0.3.0

func (b *Banhammer) ReactOn() []string

ReactOn keys

type BroadcastParams

type BroadcastParams struct {
	URL          string        // URL for "ping"
	PingInterval time.Duration // Ping interval
	DelayToOff   time.Duration // State will be switched to off in no ok replies from URL in this interval
	Client       http.Client   // http client
}

BroadcastParams defines parameters for broadcast detection

type BroadcastStatus

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

BroadcastStatus bot replies with current broadcast status

func NewBroadcastStatus

func NewBroadcastStatus(ctx context.Context, params BroadcastParams) *BroadcastStatus

NewBroadcastStatus starts status checking goroutine and returns bot instance

func (*BroadcastStatus) Help

func (b *BroadcastStatus) Help() string

Help returns help message

func (*BroadcastStatus) OnMessage

func (b *BroadcastStatus) OnMessage(_ Message) (response Response)

OnMessage returns current broadcast status if it was changed

func (*BroadcastStatus) ReactOn

func (b *BroadcastStatus) ReactOn() []string

ReactOn keys

type Duck

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

Duck bot, returns from duckduckgo via mashape

func NewDuck

func NewDuck(key string, client HTTPClient) *Duck

NewDuck makes a bot for duckduckgo

func (*Duck) Help

func (d *Duck) Help() string

Help returns help message

func (*Duck) OnMessage

func (d *Duck) OnMessage(msg Message) (response Response)

OnMessage pass msg to all bots and collects responses

func (*Duck) ReactOn

func (d *Duck) ReactOn() []string

ReactOn keys

type Entity

type Entity struct {
	Type   string
	Offset int
	Length int
	URL    string `json:",omitempty"` // For “text_link” only, url that will be opened after user taps on the text
	User   *User  `json:",omitempty"` // For “text_mention” only, the mentioned user
}

Entity represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

type Excerpt

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

Excerpt bot, returns link excerpt

func NewExcerpt

func NewExcerpt(api, token string) *Excerpt

NewExcerpt makes a bot extracting articles excerpt

func (*Excerpt) Help

func (e *Excerpt) Help() string

Help returns help message

func (*Excerpt) OnMessage

func (e *Excerpt) OnMessage(msg Message) (response Response)

OnMessage pass msg to all bots and collects responses

func (*Excerpt) ReactOn

func (e *Excerpt) ReactOn() []string

ReactOn keys

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient wrap http.Client to allow mocking

type Host added in v0.3.0

type Host struct {
	Name     string
	Timezone string
}

Host is structure with name and timezone

type Image

type Image struct {
	// FileID corresponds to Telegram file_id
	FileID   string
	Width    int
	Height   int
	Caption  string    `json:",omitempty"`
	Entities *[]Entity `json:",omitempty"`
}

Image represents image

type Interface

type Interface interface {
	OnMessage(msg Message) (response Response)
	ReactOn() []string
	Help() string
}

Interface is a bot reactive spec. response will be sent if "send" result is true

type InterfaceMock added in v0.3.0

type InterfaceMock struct {
	// HelpFunc mocks the Help method.
	HelpFunc func() string

	// OnMessageFunc mocks the OnMessage method.
	OnMessageFunc func(msg Message) Response

	// ReactOnFunc mocks the ReactOn method.
	ReactOnFunc func() []string
	// contains filtered or unexported fields
}

InterfaceMock is a mock implementation of Interface.

func TestSomethingThatUsesInterface(t *testing.T) {

	// make and configure a mocked Interface
	mockedInterface := &InterfaceMock{
		HelpFunc: func() string {
			panic("mock out the Help method")
		},
		OnMessageFunc: func(msg Message) Response {
			panic("mock out the OnMessage method")
		},
		ReactOnFunc: func() []string {
			panic("mock out the ReactOn method")
		},
	}

	// use mockedInterface in code that requires Interface
	// and then make assertions.

}

func (*InterfaceMock) Help added in v0.3.0

func (mock *InterfaceMock) Help() string

Help calls HelpFunc.

func (*InterfaceMock) HelpCalls added in v0.3.0

func (mock *InterfaceMock) HelpCalls() []struct {
}

HelpCalls gets all the calls that were made to Help. Check the length with:

len(mockedInterface.HelpCalls())

func (*InterfaceMock) OnMessage added in v0.3.0

func (mock *InterfaceMock) OnMessage(msg Message) Response

OnMessage calls OnMessageFunc.

func (*InterfaceMock) OnMessageCalls added in v0.3.0

func (mock *InterfaceMock) OnMessageCalls() []struct {
	Msg Message
}

OnMessageCalls gets all the calls that were made to OnMessage. Check the length with:

len(mockedInterface.OnMessageCalls())

func (*InterfaceMock) ReactOn added in v0.3.0

func (mock *InterfaceMock) ReactOn() []string

ReactOn calls ReactOnFunc.

func (*InterfaceMock) ReactOnCalls added in v0.3.0

func (mock *InterfaceMock) ReactOnCalls() []struct {
}

ReactOnCalls gets all the calls that were made to ReactOn. Check the length with:

len(mockedInterface.ReactOnCalls())

type Message

type Message struct {
	ID         int
	From       User
	SenderChat SenderChat `json:"sender_chat,omitempty"`
	ChatID     int64
	Sent       time.Time
	HTML       string    `json:",omitempty"`
	Text       string    `json:",omitempty"`
	Entities   *[]Entity `json:",omitempty"`
	Image      *Image    `json:",omitempty"`
	ReplyTo    struct {
		From       User
		Text       string `json:",omitempty"`
		Sent       time.Time
		SenderChat SenderChat `json:"sender_chat,omitempty"`
	} `json:",omitempty"`
}

Message is primary record to pass data from/to bots

type MultiBot

type MultiBot []Interface

MultiBot combines many bots to one virtual

func (MultiBot) Help

func (b MultiBot) Help() string

Help returns help message

func (MultiBot) OnMessage

func (b MultiBot) OnMessage(msg Message) (response Response)

OnMessage pass msg to all bots and collects responses (combining all of them) noinspection GoShadowedVar

func (MultiBot) ReactOn

func (b MultiBot) ReactOn() (res []string)

ReactOn returns combined list of all keywords

type News

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

News bot, returns numArticles last articles in MD format from https://news.radio-t.com/api/v1/news/lastmd/5

func NewNews

func NewNews(client HTTPClient, api string, maximum int) *News

NewNews makes new News bot

func (News) Help

func (n News) Help() string

Help returns help message

func (News) OnMessage

func (n News) OnMessage(msg Message) (response Response)

OnMessage returns N last news articles

func (News) ReactOn

func (n News) ReactOn() []string

ReactOn keys

type Podcasts

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

Podcasts search bot, returns search result via site-api see https://radio-t.com/api-docs/ GET /search?q=text-to-search&skip=10&limit=5, example: : https://radio-t.com/site-api/search?q=mongo&limit=10

func NewPodcasts

func NewPodcasts(client HTTPClient, api string, maxResults int) *Podcasts

NewPodcasts makes new Podcasts bot

func (*Podcasts) Help

func (p *Podcasts) Help() string

Help returns help message

func (*Podcasts) OnMessage

func (p *Podcasts) OnMessage(msg Message) (response Response)

OnMessage returns result of search via https://radio-t.com/site-api/search?

func (*Podcasts) ReactOn

func (p *Podcasts) ReactOn() []string

ReactOn keys

type PrepPost

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

PrepPost bot notifies on new prep topic on the site

func NewPrepPost

func NewPrepPost(client HTTPClient, api string, d time.Duration) *PrepPost

NewPrepPost makes new PrepPost bot sending and pinning message "Начался сбор тем"

func (*PrepPost) Help

func (p *PrepPost) Help() string

Help returns help message

func (*PrepPost) OnMessage

func (p *PrepPost) OnMessage(Message) (response Response)

OnMessage reacts on any message and, from time to time (every checkDuration) hits site api and gets the latest prep article. In case if article's url changed returns pinned response. Skips the first check to avoid false-positive on restart

func (*PrepPost) ReactOn

func (p *PrepPost) ReactOn() []string

ReactOn keys

type Response

type Response struct {
	Text          string
	Send          bool          // status
	Pin           bool          // enable pin
	Unpin         bool          // enable unpin
	Preview       bool          // enable web preview
	BanInterval   time.Duration // bots banning user set the interval
	User          User          // user to ban
	ChannelID     int64         // channel to ban, if set then User and BanInterval are ignored
	ReplyTo       int           // message to reply to, if 0 then no reply but common message
	ParseMode     string        // parse mode for message in Telegram (we use Markdown by default)
	DeleteReplyTo bool          // delete message what bot replays to
}

Response describes bot's answer on particular message

type SenderChat added in v0.3.0

type SenderChat struct {
	// ID is a unique identifier for this chat
	ID int64 `json:"id"`
	// field below used only for logging purposes
	// UserName for private chats, supergroups and channels if available, optional
	UserName string `json:"username,omitempty"`
}

SenderChat is the sender of the message, sent on behalf of a chat. The channel itself for channel messages. The supergroup itself for messages from anonymous group administrators. The linked channel for messages automatically forwarded to the discussion group

type SpamFilter added in v0.3.0

type SpamFilter struct {
	SpamParams
	// contains filtered or unexported fields
}

SpamFilter bot, checks if user is a spammer using internal matching as well as CAS API

func NewSpamFilter added in v0.3.0

func NewSpamFilter(p SpamParams) *SpamFilter

NewSpamFilter makes a spam detecting bot

func (*SpamFilter) Help added in v0.3.0

func (s *SpamFilter) Help() string

Help returns help message

func (*SpamFilter) OnMessage added in v0.3.0

func (s *SpamFilter) OnMessage(msg Message) (response Response)

OnMessage checks if user already approved and if not checks if user is a spammer

func (*SpamFilter) ReactOn added in v0.3.0

func (s *SpamFilter) ReactOn() []string

ReactOn keys

type SpamParams added in v0.3.0

type SpamParams struct {
	SuperUser           SuperUser
	SpamSamples         io.Reader
	SimilarityThreshold float64
	MinMsgLen           int
	CasAPI              string
	HTTPClient          HTTPClient
	Dry                 bool
}

SpamParams is a full set of parameters for spam bot

type StackOverflow

type StackOverflow struct{}

StackOverflow bot, returns from "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow" reacts on "so!" prefix, i.e. "so! golang"

func NewStackOverflow

func NewStackOverflow() *StackOverflow

NewStackOverflow makes a bot for SO

func (StackOverflow) Help

func (s StackOverflow) Help() string

Help returns help message

func (StackOverflow) OnMessage

func (s StackOverflow) OnMessage(msg Message) (response Response)

OnMessage returns one entry

func (StackOverflow) ReactOn

func (s StackOverflow) ReactOn() []string

ReactOn keys

type SuperUser

type SuperUser interface {
	IsSuper(userName string) bool
}

SuperUser defines interface checking ig user name in su list

type Sys

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

Sys implements basic bot function to respond on ping and others from basic.data file. also, reacts on say! with keys/values from say.data file

func NewSys

func NewSys(dataLocation string) (*Sys, error)

NewSys makes new sys bot and load data to []say and basic map

func (*Sys) Help

func (p *Sys) Help() (line string)

Help returns help message

func (*Sys) OnMessage

func (p *Sys) OnMessage(msg Message) (response Response)

OnMessage implements bot.Interface

func (*Sys) ReactOn

func (p *Sys) ReactOn() []string

ReactOn keys

type TgBanClient added in v0.3.0

type TgBanClient interface {
	Request(c tbapi.Chattable) (*tbapi.APIResponse, error)
}

TgBanClient is a subset of tg api limited to ban-related operations only

type User

type User struct {
	ID          int64
	Username    string
	DisplayName string
}

User defines user info of the Message

type WTF

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

WTF bot bans user for random interval

func NewWTF

func NewWTF(minDuration, maxDuration time.Duration, superUser SuperUser) *WTF

NewWTF makes a random ban bot

func (*WTF) Help

func (w *WTF) Help() string

Help returns help message

func (*WTF) OnMessage

func (w *WTF) OnMessage(msg Message) (response Response)

OnMessage sets duration of ban randomly

func (*WTF) ReactOn

func (w *WTF) ReactOn() []string

ReactOn keys

type WTFSteroidChecker added in v0.3.0

type WTFSteroidChecker struct {
	Message string
}

WTFSteroidChecker check if command wtf{!,?} is written with additional characters "𝀥tf!" should be recognized as "wtf?" and so on

func (*WTFSteroidChecker) CleanUp added in v0.3.0

func (w *WTFSteroidChecker) CleanUp()

CleanUp remove all bad symbols from message

func (*WTFSteroidChecker) Contains added in v0.3.0

func (w *WTFSteroidChecker) Contains() bool

Contains remove all bad symbols from message and check if the message contained the commands

func (*WTFSteroidChecker) ContainsWTF added in v0.3.0

func (w *WTFSteroidChecker) ContainsWTF() bool

ContainsWTF remove all bad symbols from message and check if the message contained substring with "wtf"

func (*WTFSteroidChecker) WTFUnicodeDiacriticLibrary added in v0.3.0

func (w *WTFSteroidChecker) WTFUnicodeDiacriticLibrary() map[string][]string

WTFUnicodeDiacriticLibrary contains diacritic unicode symbols that looks like "w","t","f","!","?" All symbols that removes by removeDiacritic function

func (*WTFSteroidChecker) WTFUnicodeLibrary added in v0.3.0

func (w *WTFSteroidChecker) WTFUnicodeLibrary() map[string][]string

WTFUnicodeLibrary contains unicode characters and strings that looks like "w","t","f","!","?"

type WhatsTheTime added in v0.3.0

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

WhatsTheTime answers which time is on hosts timezones uses whatsthetime.data file as configuration

func NewWhatsTheTime added in v0.3.0

func NewWhatsTheTime(dataLocation string) (*WhatsTheTime, error)

NewWhatsTheTime makes new What's The Time bot and load data to []hosts

func (*WhatsTheTime) Help added in v0.3.0

func (w *WhatsTheTime) Help() (line string)

Help returns help message

func (*WhatsTheTime) OnMessage added in v0.3.0

func (w *WhatsTheTime) OnMessage(msg Message) (response Response)

OnMessage returns one entry

func (*WhatsTheTime) ReactOn added in v0.3.0

func (w *WhatsTheTime) ReactOn() []string

ReactOn returns reaction keys

type When added in v0.3.0

type When struct{}

When bot is answer on question "when the stream is started".

func NewWhen added in v0.3.0

func NewWhen() *When

NewWhen makes a new When bot.

func (*When) Help added in v0.3.0

func (w *When) Help() string

Help returns help message

func (*When) OnMessage added in v0.3.0

func (w *When) OnMessage(msg Message) Response

OnMessage returns one entry

func (*When) ReactOn added in v0.3.0

func (w *When) ReactOn() []string

ReactOn keys

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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