Documentation
¶
Overview ¶
Package mgram monetizes Telegram bots with MGRAM (https://mgram.biz): sponsor tasks before the bot's answer (force subscribe) and Reply Ads after it.
The key is the Bot API key from @mgram (bot stats → Settings → API access). Keep it on the server only.
client := mgram.New(os.Getenv("MGRAM_API_KEY"))
tasks, err := client.GetTasks(ctx, mgram.User{ID: userID, LanguageCode: "en"})
if !tasks.Skip {
// show tasks.Pending() as URL buttons and a "Check" button that calls CheckTasks
}
ad, err := client.ShowAd(ctx, mgram.User{ID: userID}, messageID) // after a useful answer
GetTasks, CheckTasks and ShowAd fail open: on a network or API error they still return a result that lets the user through (Skip: true, Shown: false) together with the error, so a bot never breaks because of ads.
Example ¶
Sponsor tasks before the bot's answer and a Reply Ad after it.
package main
import (
"context"
"fmt"
"os"
mgram "github.com/mgram-web/mgram-go"
)
func main() {
ctx := context.Background()
client := mgram.New(os.Getenv("MGRAM_API_KEY"))
tasks, _ := client.GetTasks(ctx, mgram.User{ID: 12345, LanguageCode: "en"})
if !tasks.Skip {
for _, t := range tasks.Pending() {
fmt.Println(t.Button(), t.Link) // URL buttons, then a "Check" button that calls CheckTasks
}
return
}
// ... answer the user, then:
_, _ = client.ShowAd(ctx, mgram.User{ID: 12345}, 0)
}
Output:
Index ¶
- Constants
- func VerifySignature(secret, timestamp string, body []byte, signature string, maxAge time.Duration) bool
- type AdResult
- type Client
- func (c *Client) Bot(ctx context.Context) (map[string]any, error)
- func (c *Client) CheckTasks(ctx context.Context, userID int64, taskIDs []int64) (*Tasks, error)
- func (c *Client) Do(ctx context.Context, method, path string, body, out any) error
- func (c *Client) Earnings(ctx context.Context) (map[string]any, error)
- func (c *Client) GetTasks(ctx context.Context, u User) (*Tasks, error)
- func (c *Client) GetTasksLimit(ctx context.Context, u User, limit int) (*Tasks, error)
- func (c *Client) SetWebhook(ctx context.Context, url string, rotateSecret bool) (map[string]any, error)
- func (c *Client) ShowAd(ctx context.Context, u User, messageID int64) (*AdResult, error)
- type Error
- type Event
- type Option
- type Task
- type Tasks
- type User
Examples ¶
Constants ¶
const BaseURL = "https://api.mgram.biz"
BaseURL is the MGRAM API.
const Version = "1.0.0"
Version of this SDK, sent in the User-Agent.
Variables ¶
This section is empty.
Functions ¶
func VerifySignature ¶
func VerifySignature(secret, timestamp string, body []byte, signature string, maxAge time.Duration) bool
VerifySignature reports whether a webhook request really comes from MGRAM. Headers: X-MGRAM-Timestamp and X-MGRAM-Signature = "sha256=" + HMAC_SHA256(secret, timestamp + "." + raw body). maxAge rejects old requests (0 — do not check the age).
Types ¶
type AdResult ¶
type AdResult struct {
Shown bool `json:"shown"`
Reason string `json:"reason"`
DeliveryID string `json:"delivery_id,omitempty"`
MessageID int64 `json:"message_id,omitempty"`
// RetryAfter is the number of seconds until the next ad may be shown to this user (Reason "frequency").
RetryAfter int `json:"retry_after,omitempty"`
}
AdResult is the answer of POST /reply-ads/show. Shown means your bot has already sent the ad.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls the MGRAM API. The zero value is not usable: create it with New.
func (*Client) CheckTasks ¶
CheckTasks returns fresh statuses for the "Check" button (POST /tasks/check). taskIDs may be nil. Safe to repeat.
func (*Client) Do ¶
Do calls any API method and decodes its "data" object into out (which may be nil).
func (*Client) GetTasks ¶
GetTasks returns sponsor tasks for a user (POST /tasks). On an error it fails open: Skip is true and the error is returned too.
func (*Client) GetTasksLimit ¶
GetTasksLimit is GetTasks with the number of tasks to show at once.
func (*Client) SetWebhook ¶
func (c *Client) SetWebhook(ctx context.Context, url string, rotateSecret bool) (map[string]any, error)
SetWebhook sends task.completed / task.refunded events to url (POST /tasks/webhook). An empty url turns it off.
type Error ¶
Error is an MGRAM API error ({"ok": false, "error": {"code", "message"}}), or Code "network" / "bad_response".
type Event ¶
type Event struct {
Event string `json:"event"`
UserID int64 `json:"user_id"`
Skip bool `json:"skip"`
Task *Task `json:"task"`
Timestamp int64 `json:"timestamp"`
}
Event is a webhook event: "task.completed" or "task.refunded".
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithBaseURL ¶
WithBaseURL points the client at another API address (tests, proxies).
func WithHTTPClient ¶
WithHTTPClient replaces the default http.Client (5 s timeout).
type Task ¶
type Task struct {
ID int64 `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
Link string `json:"link"`
ButtonText string `json:"button_text"`
Status string `json:"status"`
Payout string `json:"payout"`
Reward json.RawMessage `json:"reward,omitempty"`
Currency string `json:"currency,omitempty"`
Username string `json:"username,omitempty"`
}
Task is one sponsor task: join a channel or a group, or start a bot.
type Tasks ¶
type Tasks struct {
Skip bool `json:"skip"`
Status string `json:"status"`
Tasks []Task `json:"tasks"`
Earned json.RawMessage `json:"earned,omitempty"`
}
Tasks is the answer of POST /tasks and /tasks/check. Skip means there is nothing to do (no tasks, all done, or the API was unreachable): let the user through. Status: "tasks", "completed", "no_tasks", or "error" when the SDK failed open.
type User ¶
type User struct {
ID int64 `json:"user_id"`
LanguageCode string `json:"language_code,omitempty"`
IsPremium bool `json:"is_premium,omitempty"`
FirstName string `json:"first_name,omitempty"`
Username string `json:"username,omitempty"`
// InitData is Telegram.WebApp.initData for Mini Apps.
InitData string `json:"init_data,omitempty"`
}
User is the Telegram user the request is about. Only ID is required.