mgram

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

MGRAM SDK for Go

tests Go Reference license

Monetize a Telegram bot with MGRAM: sponsor tasks before the answer (force subscribe) and Reply Ads after it. Standard library only, works with any bot library: go-telegram/bot, telebot, telegram-bot-api.

If MGRAM is unreachable or has nothing to show, users simply go through, so your bot never breaks.

Install

go get github.com/mgram-web/mgram-go

Get the key: connect your bot in @mgram, then bot stats → Settings → API access.

Usage

client := mgram.New(os.Getenv("MGRAM_API_KEY"))

// before answering: sponsor tasks (force subscribe)
tasks, _ := client.GetTasks(ctx, mgram.User{ID: from.ID, LanguageCode: from.LanguageCode})
if !tasks.Skip {
    // show tasks.Pending() as URL buttons + a "Check" button
    return
}

// the "Check" button
tasks, _ = client.CheckTasks(ctx, from.ID, nil)

// after a useful answer: a Reply Ad sent by your bot
ad, _ := client.ShowAd(ctx, mgram.User{ID: from.ID}, msg.ID)

GetTasks, CheckTasks and ShowAd never block users on errors: a network or API error returns Skip: true (or Shown: false) together with the error, so you can log it and go on.

Webhooks

http.HandleFunc("/mgram", func(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    if !mgram.VerifySignature(secret, r.Header.Get("X-MGRAM-Timestamp"), body, r.Header.Get("X-MGRAM-Signature"), 5*time.Minute) {
        w.WriteHeader(http.StatusUnauthorized)
        return
    }
    event, _ := mgram.ParseEvent(body) // task.completed · task.refunded
    _ = event
})

API

Method Endpoint What it does
GetTasks(ctx, user) POST /tasks Sponsor tasks for a user; Skip means let the user through
CheckTasks(ctx, userID, taskIDs) POST /tasks/check Fresh statuses for the "Check" button
ShowAd(ctx, user, messageID) POST /reply-ads/show A Reply Ad sent by your bot; Reason and RetryAfter when nothing is shown
SetWebhook(ctx, url, rotate) POST /tasks/webhook Events task.completed and task.refunded to your server
Bot(ctx) · Earnings(ctx) GET /bot · GET /earnings The bot behind the key and its earnings
Do(ctx, method, path, body, out) any Any other API method

What you earn

Format From bot size Paid to you
Sponsor tasks the first user per subscription or bot start that Telegram confirms
Reply Ads 50 users per 1,000 delivered impressions

The bot owner gets 70% of every placement. Farms and repeats are never paid. Payouts in USDT to CryptoBot or a TON wallet. Current rates: mgram.biz/en/pricing.

Website mgram.biz
Connect a bot @mgram
API docs api.mgram.biz · OpenAPI
Other SDKs Python · JavaScript · Go
For advertisers MCP server for Claude and ChatGPT
Support support@mgram.biz · @mgram

MIT License

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)
}

Index

Examples

Constants

View Source
const BaseURL = "https://api.mgram.biz"

BaseURL is the MGRAM API.

View Source
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 New

func New(apiKey string, opts ...Option) *Client

New returns a client for the Bot API key from @mgram.

func (*Client) Bot

func (c *Client) Bot(ctx context.Context) (map[string]any, error)

Bot returns the bot behind the key (GET /bot).

func (*Client) CheckTasks

func (c *Client) CheckTasks(ctx context.Context, userID int64, taskIDs []int64) (*Tasks, error)

CheckTasks returns fresh statuses for the "Check" button (POST /tasks/check). taskIDs may be nil. Safe to repeat.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) error

Do calls any API method and decodes its "data" object into out (which may be nil).

func (*Client) Earnings

func (c *Client) Earnings(ctx context.Context) (map[string]any, error)

Earnings returns what the bot has earned (GET /earnings).

func (*Client) GetTasks

func (c *Client) GetTasks(ctx context.Context, u User) (*Tasks, error)

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

func (c *Client) GetTasksLimit(ctx context.Context, u User, limit int) (*Tasks, error)

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.

func (*Client) ShowAd

func (c *Client) ShowAd(ctx context.Context, u User, messageID int64) (*AdResult, error)

ShowAd shows a Reply Ad after a useful answer (POST /reply-ads/show); MGRAM sends it on behalf of your bot. messageID is the user's message you answered (0 to omit). On an error Shown is false and Reason is the error code.

type Error

type Error struct {
	Code    string
	Message string
	Status  int
}

Error is an MGRAM API error ({"ok": false, "error": {"code", "message"}}), or Code "network" / "bad_response".

func (*Error) Error

func (e *Error) Error() string

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".

func ParseEvent

func ParseEvent(body []byte) (*Event, error)

ParseEvent decodes a webhook body.

func (Event) Completed

func (e Event) Completed() bool

Completed reports a task the user has completed.

func (Event) Refunded

func (e Event) Refunded() bool

Refunded reports a task taken back (for example, the user left the channel).

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL points the client at another API address (tests, proxies).

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

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.

func (Task) Button

func (t Task) Button() string

Button is the text for the task's URL button.

func (Task) Done

func (t Task) Done() bool

Done reports whether the user has completed the task.

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.

func (*Tasks) Pending

func (t *Tasks) Pending() []Task

Pending returns the tasks the user has not completed yet.

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.

Jump to

Keyboard shortcuts

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