Nigel  Uys

Nigel Uys

1663139820

10 Popular Libraries for Building and Working with Bots in Go

In today's post we will learn about 10 Popular Libraries for Building and Working with Bots in Go.

Go programing language is shortened as Golang. It is a trusted open source and effective language for developing software applications.

A bot can also be called a robot or internet bot. It’s a program that serves as an agent for taking charge of repeated tasks that should have been done by a user.

These bots don’t just appear on their own, there are some peculiar languages used in building them – Go language is one of those languages.

Follow us as we explain here in detail some important bot building in Go programing language.

Table of contents:

  • Echotron - An elegant and concurrent library for Telegram Bots in Go.
  • Ephemeral-roles - A Discord bot for managing ephemeral roles based upon voice channel member presence.
  • Go-chat-bot - IRC, Slack & Telegram bot written in Go.
  • Kelp - A free and open-source trading bot for the Stellar DEX and 100+ centralized exchanges.
  • Go-sarah - Framework to build bot for desired chat services including LINE, Slack, Gitter and more.
  • Go-tgbot - Pure Golang Telegram Bot API wrapper, generated from swagger file, session-based router and middleware.
  • Go-twitch-irc - Library to write bots for twitch.tv chat
  • Golang CryptoTrading Bot - A golang implementation of a console-based trading bot for cryptocurrency exchanges.
  • Govkbot - Simple Go VK bot library.
  • Hanu - Framework for writing Slack bots.

1 - Echotron: An elegant and concurrent library for Telegram Bots in Go.

Echotron is a concurrent library for telegram bots written in pure Go.

Fetch with

go get github.com/NicoNex/echotron/v3

Usage

Long Polling

A very simple implementation:

package main

import (
	"log"

	"github.com/NicoNex/echotron/v3"
)

// Struct useful for managing internal states in your bot, but it could be of
// any type such as `type bot int64` if you only need to store the chatID.
type bot struct {
	chatID int64
	echotron.API
}

const token = "YOUR TELEGRAM TOKEN"

// This function needs to be of type 'echotron.NewBotFn' and is called by
// the echotron dispatcher upon any new message from a chatID that has never
// interacted with the bot before.
// This means that echotron keeps one instance of the echotron.Bot implementation
// for each chat where the bot is used.
func newBot(chatID int64) echotron.Bot {
	return &bot{
		chatID,
		echotron.NewAPI(token),
	}
}

// This method is needed to implement the echotron.Bot interface.
func (b *bot) Update(update *echotron.Update) {
	if update.Message.Text == "/start" {
		b.SendMessage("Hello world", b.chatID, nil)
	}
}

func main() {
	// This is the entry point of echotron library.
	dsp := echotron.NewDispatcher(token, newBot)
	log.Println(dsp.Poll())
}

View on Github

2 - Ephemeral-roles: A Discord bot for managing ephemeral roles based upon voice channel member presence.

Quickstart

  1. Click on the Ephemeral Roles logo head above or use this link to invite Ephemeral Roles into your Discord server
    1. The 'Manage Roles' permission is required. The invite link above provides that by automatically creating an appropriate role in your server for Ephemeral Roles
  2. Ensure the new role for Ephemeral Roles is at the top (or as near as possible) to the server's list of roles
    1. If you're not sure how or why to do that, take a quick read over Discord's excellent Role Management 101 guide
  3. Enjoy!

What does Ephemeral Roles do?

After the Ephemeral Roles bot is invited to your Discord server, it immediately starts to watch for changes to your voice channels. When a member joins a channel, Ephemeral Roles automatically assigns that member an ephemeral role associated with the channel. If the ephemeral role doesn't exist yet, Ephemeral Roles will create it.

By having your members auto-sorted into ephemeral roles in your member list, it's clear to see who are available for chatting and the channels they are in. This is because Ephemeral Roles leverages the Discord feature that the member list in servers will group together members by role right out of the box.

When a member changes or disconnects from voice channels, even across Discord servers, Ephemeral Roles will account for the change and automatically revoke/reissue ephemeral roles as appropriate.

Example Usage

Orange roles below are automatically managed by Ephemeral Roles
Ephemeral Roles action example
Ephemeral Roles static example
Ephemeral Roles example role list

View on Github

3 - Go-chat-bot: IRC, Slack & Telegram bot written in Go.

IRC, Slack & Telegram bot written in Go using go-ircevent for IRC connectivity, nlopes/slack for Slack and Syfaro/telegram-bot-api for Telegram.

Plugins

Please see the plugins repository for a complete list of plugins.

You can also write your own, it's really simple.

Compiling and testing the bot and plugins (Debug)

This project uses the new Go 1.11 modules if you have Go 1.11 installed, just clone the project and follow the instructions bellow, when you build Go will automatically download all dependencies.

To test the bot, use the debug console app.

  • Clone this repository or use go get github.com/go-chat-bot/bot
  • Build everything: go build ./...
  • Build and execute the debug app:
    • cd debug
    • go build
    • ./debug
  • This will open a console where you can type commands
  • Type !help to see the list of available commands

Testing your plugin

  • Add your plugin to debug/main.go import list
  • Build the debug app
  • Execute it and test with the interactive console

Protocols

Slack

To deploy your go-bot to Slack, you need to:

  • Create a new bot user integration on Slack and get your token
  • Import the package github.com/go-chat-bot/bot/slack
  • Import the commands you would like to use
  • Call slack.Run(token)

Here is a full example reading the Slack token from the SLACK_TOKEN env var:

package main

import (
    "os"

    "github.com/go-chat-bot/bot/slack"
    _ "github.com/go-chat-bot/plugins/catfacts"
    _ "github.com/go-chat-bot/plugins/catgif"
    _ "github.com/go-chat-bot/plugins/chucknorris"
    // Import all the commands you wish to use
)

func main() {
    slack.Run(os.Getenv("SLACK_TOKEN"))
}

View on Github

4 - Kelp: A free and open-source trading bot for the Stellar DEX and 100+ centralized exchanges.

Kelp is a free and open-source trading bot for the Stellar universal marketplace and for centralized exchanges such as Binance, Kraken, CoinbasePro, etc.

Kelp includes several configurable trading strategies and exchange integrations. You can define your own parameters or use the sample configurations to quickly get up and running with a trading bot in a matter of minutes. The modular design allows you to easily create new trading strategies, exchange integrations, and assets to give you full control over the bot.

Getting Started

How To Get Kelp

To get started with Kelp, either download the pre-compiled binary for your platform from the Github Releases Page or compile Kelp from source.

There is one binary associated with this project: kelp. Once the binary is downloaded, run the bot by following the instructions in Running Kelp.

Download Kelp Binary

You can find the pre-compiled binary for your platform from the Github Releases Page.

GUI

Here is a list of binaries for the most recent release v1.0.0-rc2 (v1.12.0):

PlatformArchitectureBinary File Name
MacOS (Darwin)64-bitkelp-v1.12.0-darwin-amd64.tar
Windows64-bitkelp-v1.12.0-windows-amd64.tar
Linux64-bitkelp-v1.12.0-linux-amd64.tar

CLI

Here is a list of binaries for the most recent release v1.12.0:

PlatformArchitectureBinary File Name
MacOS (Darwin)64-bitkelp-v1.12.0-darwin-amd64.tar
Windows64-bitkelp-v1.12.0-windows-amd64.tar
Linux64-bitkelp-v1.12.0-linux-amd64.tar
Linux64-bit armkelp-v1.12.0-linux-arm64.tar
Linux32-bit arm5kelp-v1.12.0-linux-arm5.tar
Linux32-bit arm6kelp-v1.12.0-linux-arm6.tar
Linux32-bit arm7kelp-v1.12.0-linux-arm7.tar

After you untar the downloaded file, change to the generated directory (kelp-v1.12.0) and invoke the kelp binary.

Here's an example to get you started (replace filename with the name of the file that you download):

tar xvf filename
cd kelp-v1.12.0
./kelp

To run the bot in simulation mode, try this command:

./kelp trade -c sample_trader.cfg -s buysell -f sample_buysell.cfg --sim

View on Github

5 - Go-sarah: Framework to build bot for desired chat services including LINE, Slack, Gitter and more.

Introduction

Sarah is a general-purpose bot framework named after the author's firstborn daughter.

This comes with a unique feature called "stateful command" as well as some basic features such as commands and scheduled tasks. In addition to those fundamental features, this project provides rich life cycle management including live configuration update, customizable alerting mechanism, automated command/task (re)building, and panic-proofed concurrent command/task execution.

Such features are achieved with a composition of fine-grained components. Each component has its own interface and a default implementation, so developers are free to customize their bot experience by replacing the default implementation for a particular component with their own implementation. Thanks to such segmentalized lifecycle management architecture, the adapter component to interact with each chat service has fewer responsibilities compared to other bot frameworks; An adapter developer may focus on implementing the protocol to interact with the corresponding chat service. To take a look at those components and their relations, see Components.

IMPORTANT NOTICE

v4 Release

This is the fourth major version of go-sarah, which involves some architectural changes:

  • sarah.NewBot now returns a single value: sarah.Bot
  • Utility packages including logger, retry, and worker are now hosted by github.com/oklahomer/go-kasumi

v3 Release

This is the third major version of go-sarah, which introduces the Slack adapter's improvement to support both RTM and Events API. Breaking interface changes for the Slack adapter was inevitable and that is the sole reason for this major version up. Other than that, this does not include any breaking change. See Migrating from v2.x to v3.x for details.

v2 Release

The second major version introduced some breaking changes to go-sarah. This version still supports and maintains all functionalities, while better interfaces for easier integration are introduced. See Migrating from v1.x to v2.x to migrate from the older version.

At a Glance

General Command Execution

hello world

Above is a general use of go-sarah. Registered commands are checked against the user input and the matching one is executed; when a user inputs ".hello," hello command is executed and a message "Hello, 世界" is returned.

Stateful Command Execution

The below image depicts how a command with a user's conversational context works. The idea and implementation of "user's conversational context" is go-sarah's signature feature that makes a bot command "state-aware."

The above example is a good way to let a user input a series of arguments in a conversational manner. Below is another example that uses a stateful command to entertain the user.

View on Github

6 - Go-tgbot: Pure Golang Telegram Bot API wrapper, generated from swagger file, session-based router and middleware.

Pure Golang telegram bot API wrapper generated from swagger definition, session-based routing and middlewares.

Usage benefits

  1. No need to learn any other library API. You will use methods with payload exactly like it presented on telegram bot API description page. With only couple trade-offs, b/c of telegram bot API is generics a bit.
  2. All models and methods are being supported. The models and methods were generated from swagger.yaml description file. So, new entities/methods could be added by describing in the YAML swagger file. This approach allows validating the description, avoid typos and develop fast.
  3. easyjson is plugged. So, it's fast.
  4. context.Context based HTTP client
  5. Session-based routing, not only message text based.

Client

Client package could be used as regular go-swagger client library without using Router. There are the only two additional features over go-swagger, a possibility to setup token by default(It solved as an interface checking) and API throttling for 30 calls per second(see more info).

Example:

package main

import (
	"context"
	"flag"
	"log"
	"time"

	tgbot "github.com/olebedev/go-tgbot"
	"github.com/olebedev/go-tgbot/client/users"
)

var token *string

func main() {
	token = flag.String("token", "", "telegram bot token")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	api := tgbot.NewClient(ctx, *token)

	log.Println(api.Users.GetMe(nil))

	// Also, every calls could be done with given context
	ctx, cancel = context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	_, err := api.Users.GetMe(
		users.NewGetMeParams().
			WithContext(ctx),
	)

	if err != nil {
		// users.NewGetMeBadRequest()
		if e, ok := err.(*users.GetMeBadRequest); ok {
			log.Println(e.Payload.ErrorCode, e.Payload.Description)
		}
	}
}

Since swagger covers many other platforms/technologies the same libraries could be generated for them too. See the source here - swagger.yaml.
Also, have a look at Swagger UI for telegram API(master branch).

View on Github

7 - Go-twitch-irc: Library to write bots for twitch.tv chat

This is an irc client for connecting to twitch. It handles the annoying stuff like irc tag parsing. I highly recommend reading the documentation below, but this readme gives a basic overview of the functionality.

Getting Started

package main

import (
	"fmt"

	"github.com/gempir/go-twitch-irc/v3"
)

func main() {
	// or client := twitch.NewAnonymousClient() for an anonymous user (no write capabilities)
	client := twitch.NewClient("yourtwitchusername", "oauth:123123123")

	client.OnPrivateMessage(func(message twitch.PrivateMessage) {
		fmt.Println(message.Message)
	})

	client.Join("gempir")

	err := client.Connect()
	if err != nil {
		panic(err)
	}
}

Available Data

The twitch.User and MessageType structs reflect the data Twitch provides, minus any fields that have been marked as deprecated:

type User struct {
	ID          string
	Name        string
	DisplayName string
	Color       string
	Badges      map[string]int
}

type WhisperMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Target    string
	MessageID string
	ThreadID  string
	Emotes    []*Emote
	Action    bool
}

type PrivateMessage struct {
	User User

	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	RoomID  string
	ID      string
	Time    time.Time
	Emotes  []*Emote
	Bits    int
	Action  bool
}

type ClearChatMessage struct {
	Raw            string
	Type           MessageType
	RawType        string
	Tags           map[string]string
	Message        string
	Channel        string
	RoomID         string
	Time           time.Time
	BanDuration    int
	TargetUserID   string
	TargetUsername string
}

type ClearMessage struct {
	Raw         string
	Type        MessageType
	RawType     string
	Tags        map[string]string
	Message     string
	Channel     string
	Login       string
	TargetMsgID string
}

type RoomStateMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	RoomID  string
	State   map[string]int
}

type UserNoticeMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	RoomID    string
	ID        string
	Time      time.Time
	Emotes    []*Emote
	MsgID     string
	MsgParams map[string]string
	SystemMsg string
}

type UserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	Message   string
	Channel   string
	EmoteSets []string
}

type GlobalUserStateMessage struct {
	User User

	Raw       string
	Type      MessageType
	RawType   string
	Tags      map[string]string
	EmoteSets []string
}

type NoticeMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
	Channel string
	MsgID   string
}

type UserJoinMessage struct {
	// Channel name
	Channel string

	// User name
	User string
}

type UserPartMessage struct {
	// Channel name
	Channel string

	// User name
	User string
}

For unsupported message types, we return RawMessage:

type RawMessage struct {
	Raw     string
	Type    MessageType
	RawType string
	Tags    map[string]string
	Message string
}

View on Github

8 - Golang CryptoTrading Bot: A golang implementation of a console-based trading bot for cryptocurrency exchanges.

Usage

Download a release or directly build the code from this repository.

go get github.com/saniales/golang-crypto-trading-bot

If you need to, you can create a strategy and bind it to the bot:

import bot "github.com/saniales/golang-crypto-trading-bot/cmd"

func main() {
    bot.AddCustomStrategy(examples.MyStrategy)
    bot.Execute()
}

For strategy reference see the Godoc documentation.

Simulation Mode

If enabled, the bot will do paper trading, as it will execute fake orders in a sandbox environment.

A Fake balance for each coin must be specified for each exchange if simulation mode is enabled.

Configuration file template

Create a configuration file from this example or run the init command of the compiled executable.

simulation_mode: true # if you want to enable simulation mode.
exchange_configs:
  - exchange: bitfinex
    public_key: bitfinex_public_key
    secret_key: bitfinex_secret_key
    deposit_addresses:
      BTC: bitfinex_deposit_address_btc
      ETH: bitfinex_deposit_address_eth
      ZEC: bitfinex_deposit_address_zec
    fake_balances: # used only if simulation mode is enabled, can be omitted if not enabled.
      BTC: 100
      ETH: 100
      ZEC: 100
      ETC: 100
  - exchange: hitbtc
    public_key: hitbtc_public_key
    secret_key: hitbtc_secret_key
    deposit_addresses:
      BTC : hitbtc_deposit_address_btc
      ETH: hitbtc_deposit_address_eth
      ZEC: hitbtc_deposit_address_zec
    fake_balances:
      BTC: 100
      ETH: 100
      ZEC: 100
      ETC: 100
strategies:
  - strategy: strategy_name
    markets:
      - market: ETH-BTC
        bindings:
        - exchange: bitfinex
          market_name: ETHBTC
        - exchange: hitbtc
          market_name: ETHBTC
      - market: ZEC-BTC
        bindings:
        - exchange: bitfinex
          market_name: ZECBTC
        - exchange: hitbtc
          market_name: ZECBTC
      - market: ETC-BTC
        bindings:
        - exchange: bitfinex
          market_name: ETCBTC
        - exchange: hitbtc
          market_name: ETCBTC

View on Github

9 - Govkbot: Simple Go VK bot library.

This is simple VK.com bot API.

At 2019-03-01 VK was restrict messages.send for user_tokens. This bot can work with group_token, and access to chat members if has admin rights in chat. You can use v1.0.1 also, if you need only user_token access.

It can:

  • Reply to messages (private and chat)
  • Send greetings message when invited to chat
  • Add and remove mutual friends
  • Send notifies to admin

Installatioin:

Use go mod For old Go versions you can also use go get github.com/nikepan/govkbot/v2

For work you need get VK access token with rights: messages,friends,offline (see below).

Quickstart

package main
import "github.com/nikepan/govkbot/v2"
import "log"

var VKAdminID = 3759927
var VKToken = "efjr98j9fj8jf4j958jj4985jfj9joijerf0fj548jf94jfiroefije495jf48"

func helpHandler(m *govkbot.Message) (reply string) {
  return "help received"
}

func startHandler(m *govkbot.Message) (reply govkbot.Reply) {
	keyboard := govkbot.Keyboard{Buttons: make([][]govkbot.Button, 0)}
	button := govkbot.NewButton("/help", nil)
	row := make([]govkbot.Button, 0)
	row = append(row, button)
	keyboard.Buttons = append(keyboard.Buttons, row)

	return govkbot.Reply{Msg: availableCommands, Keyboard: &keyboard}
}

func errorHandler(m *govkbot.Message, err error) {
  log.Fatal(err.Error())
}

func main() {
    //govkbot.HandleMessage("/", anyHandler)
    //govkbot.HandleMessage("/me", meHandler)
    govkbot.HandleMessage("/help", helpHandler)
    govkbot.HandleAdvancedMessage("/start", startHandler)

    //govkbot.HandleAction("chat_invite_user", inviteHandler)
    //govkbot.HandleAction("chat_kick_user", kickHandler)
    //govkbot.HandleAction("friend_add", addFriendHandler)
    //govkbot.HandleAction("friend_delete", deleteFriendHandler)

    govkbot.HandleError(errorHandler)

    govkbot.SetAutoFriend(true) // enable auto accept/delete friends

    govkbot.SetDebug(true) // log debug messages

    // Optional Direct VK API access
    govkbot.SetAPI(VKToken, "", "") // Need only before Listen, if you use direct API
    me, _ := govkbot.API.Me() // call API method
    log.Printf("current user: %+v\n", me.FullName())
    // Optional end

    govkbot.Listen(VKToken, "", "", VKAdminID)

View on Github

10 - Hanu: Framework for writing Slack bots.

The Go framework hanu is your best friend to create Slack bots! hanu uses allot for easy command and request parsing (e.g. whisper <word>) and runs fine as a Heroku worker. All you need is a Slack API token and you can create your first bot within seconds! Just have a look at the hanu-example bot or read my tutorial

Features

  • Respond to mentions
  • Respond to direct messages
  • Auto-Generated command list for help
  • Works fine as a worker on Heroku

Usage

Use the following example code or the hanu-example bot to get started.

package main

import (
	"log"
	"strings"

	"github.com/sbstjn/hanu"
)

func main() {
	slack, err := hanu.New("SLACK_BOT_API_TOKEN")

	if err != nil {
		log.Fatal(err)
	}

	Version := "0.0.1"

	slack.Command("shout <word>", func(conv hanu.ConversationInterface) {
		str, _ := conv.String("word")
		conv.Reply(strings.ToUpper(str))
	})

	slack.Command("whisper <word>", func(conv hanu.ConversationInterface) {
		str, _ := conv.String("word")
		conv.Reply(strings.ToLower(str))
	})

	slack.Command("version", func(conv hanu.ConversationInterface) {
		conv.Reply("Thanks for asking! I'm running `%s`", Version)
	})

	slack.Listen()
}

The example code above connects to Slack using SLACK_BOT_API_TOKEN as the bot's token and can respond to direct messages and mentions for the commands shout <word> , whisper <word> and version.

You don't have to care about help requests, hanu has it built in and will respond with a list of all defined commands on direct messages like this:

/msg @hanu help

Of course this works fine with mentioning you bot's username as well:

@hanu help

View on Github

Thank you for following this article.

Related videos:

A.I Bot with GO - Wit.Ai 💬+ Wolfram🐺 + Golang 🔥+ Slack 🤖

#go #golang #bot 

10 Popular Libraries for Building and Working with Bots in Go
Python  Library

Python Library

1662030060

A Template for Telegram Bot using Postgres, Redis, Python Asyncio

🚀 Getting Started

Running on Local Machine

  • install dependencies using Poetry
poetry install
  • configure environment variables in .env file
  • start bot in virtual environment
poetry run python -m bot

Launch in Docker

  • configure environment variables in .env file
  • start virtual environment
poetry shell
  • building the docker image
docker-compose build
  • start service
docker-compose up -d

🌍 Environment variables

  • BOT_TOKEN — Telegram bot token
  • PG_HOST — hostname or an IP address PostgreSQL database
  • PG_NAME — the name of the PostgreSQL database
  • PG_PASSWORD — password used to authenticate
  • PG_PORT — connection port number (defaults to 5432 if not provided)
  • PG_USER — the username used to authenticate
  • REDIS_HOST — hostname or an IP address Redis database
  • REDIS_PASSWORD — Redis database password, empty by default
  • REDIS_PORT — port from Redis database

I use Redis for Finite State Machine, and PostgreSQL as Database

🔧 Tech Stack

  • aiogram — asynchronous framework for Telegram Bot API
  • asyncpg — asynchronous PostgreSQL database client library
  • poetry — development workflow
  • loguru — third party library for logging in Python
  • docker — to automate deployment
  • postgres — powerful, open source object-relational database system
  • redis — an in-memory data structure store

Download details:

Author: donBarbos
Source code: https://github.com/donBarbos/telegram-bot-template 
License: GPL-3.0 license

#python #bot #postgres #redis #docker

A Template for Telegram Bot using Postgres, Redis, Python Asyncio
Python  Library

Python Library

1662026220

Ampalibe: A Python Framework for Building Messenger Bots Faster

Ampalibe

Ampalibe is a lightweight Python framework for building Facebook Messenger bots faster. It provides a new concept, it manages webhooks, processes data sent by Facebook and provides API Messenger with advanced functions such as payload management, item length, and more.

Installation

pip install ampalibe

OR you can install dev version

pip install https://github.com/iTeam-S/Ampalibe/archive/refs/heads/main.zip

if you use mysql as database, you have to install mysql-connector or mysql-connector-python with ampalibe

pip install ampalibe[mysql-connector]

if you use postgresql as database, you have to install psycopg2 with ampalibe

pip install ampalibe[psycopg2]

Usage

command-line ampalibe is ampalibe.bat for Windows

ampalibe create myproject

OR

$ cd myproject
$ ampalibe init

to run project, just use

ampalibe run

for dev mode with Hot Reload

ampalibe run --dev

Register for an Access Token

You will need to configure a Facebook application, a Facebook page, get the access to the page, link the application to the page, configure a webhook for your app before you can really start using Ampalibe.

This app setup guide should help

OR

See this video on Youtube

Deployment

Using container

Go to our dir project and run

$ docker run -d -v "${PWD}:/usr/src/app" -p 4555:4555 ghcr.io/iteam-s/ampalibe

Using heroku container

FROM ghcr.io/iteam-s/ampalibe

ADD . /usr/src/app/

# RUN pip install --no-cache-dir -r requirements.txt

CMD ampalibe -p $PORT run
  • Customize your Dockerfile if necessary

Using heroku python

Documentation

Other resource

Download details:

Author: iTeam-S
Source code: https://github.com/iTeam-S/Ampalibe 
License: MIT license

#python #bot

Ampalibe: A Python Framework for Building Messenger Bots Faster
Python  Library

Python Library

1661907780

SenPy: A Discord Bot Written with Discord.py

SenPy

A discord bot written with discord.py to praise your favorite waifu!

Features

Invite link

https://discord.com/oauth2/authorize?client_id=671722338848342036&scope=bot&permissions=3537984

Run your own instance of SenPy

  • Make sure Python and Git are installed on your computer
  • Open the terminal
  • Clone this repository with git clone https://github.com/kugiyasan/SenPy.git, then cd SenPy
  • Install the required modules for python pip install -r requirements.txt
  • Follow the instructions here to create a bot account
  • Rename .env.example to .env and paste your discord token obtained on the Discord Developer Portal in. In the same file, enter your database url and the default command prefix you want.
  • Enjoy! python3 src/sen.py

Download details:

Author: kugiyasan
Source code: https://github.com/kugiyasan/SenPy 
License: MIT license

#python #bot #discordbot

SenPy: A Discord Bot Written with Discord.py
Python  Library

Python Library

1661896320

Athena: Matchmaking Discord Bot Written in Python

Settings

  • Server Settings:
  • Enable/Disable Match Logging with Easy Match Report Buttons
  • Queue Embed with Join and Leave Buttons
  • Set Register Channels
  • Lobby Settings:
  • Enable/Disable Team Captain Voice Channels
  • Enable/Disable Map Picking Phase
  • Enable/Disable Team Picking Phase
  • Change Party Size

Usage

  • Lobby Commands:
  • Type (=lobby add) to create a new lobby
  • Type (=lobby del) to remove the current lobby
  • Type (=lobby show) to show all server lobbies
  • Type (=lobby settings) to show current lobby settings
  • Party Commands:
  • Type (=party create) to create a new party
  • Type (=party leave) to leave/disband party
  • Type (=party invite [@user] ) to invite an user to your party
  • Type (=party kick [@user] ) to kick an user from your party
  • Bot Commands:
  • Type (=help) to show a list of commands
  • Type (=register [name] ) to register
  • Type (=register [@user] [name] ) to register an user
  • Type (=settings) to view the settings panel and setup the bot
  • Type (=rollback [user_id] ) to undo all matches containing this user (cheaters)
  • Type (=recent) to view recent matches
  • Type (=set elo [@user] [amount] ) to set an users elo
  • Type (=set wins [@user] [amount] ) to set an users wins
  • Type (=set losses [@user] [amount] ) to set an users losses
  • Type (=join) to join the current queue
  • Type (=leave) to leave the current queue
  • Type (=reset [@user] ) to reset players stats
  • Type (=reset all) to reset everyones stats
  • Type (=clear) to clear the current queue
  • Type (=queue) to check the current queue
  • Type (=pick) to pick your teammates (team captains only)
  • Type (=addmap [name] ) to add a map
  • Type (=delmap [name] ) to delete a map
  • Type (=maps) to show a list of all maps
  • Type (=ban [@user] [time] [reason] ) to ban an user from the queue
  • Type (=unban [@user] ) to unban an user from the queue
  • Type (=match report/show/cancel/undo) to report/show/cancel/undo matches
  • Type (=win [@users] ) to give users a win
  • Type (=lose [@users] ) to give users a loss
  • Type (=unregister [@user] ) to unregister an user
  • Type (=stats) to show your stats or =stats @user
  • Type (=leaderboard) to view the elo leaderboard
  • Type (=replace [@user1] [@user2] [match_id] ) to replace an user in a match
  • Type (=lastmatch) to show the last match played
  • Type (=rename [name] ) to change your ten man name
  • Type (=forcerename [@user] [name] ) to change an users name for them
  • Type (=forcejoin [@user] ) to force join someone to the queue
  • Type (=forceleave [@user] ) to force leave someone from the queue
  • Type (=regrole [@role] ) to set the role given when an user registers

Download details:

Author: realTristan
Source code: https://github.com/realTristan/Athena 
License: MIT license

#python #bot #discordbot

Athena: Matchmaking Discord Bot Written in Python
Python  Library

Python Library

1661231880

BEE bot: OSINT Automation for Hackers Written in Python

BEE·bot

OSINT automation for hackers. BBOT is a recursive, modular OSINT framework written in Python.

It is capable of executing the entire OSINT process in a single command, including subdomain enumeration, port scanning, web screenshots (with its gowitness module), vulnerability scanning (with nuclei), and much more.

BBOT currently has over 50 modules and counting.

Installation

pipx install bbot

Prerequisites:

  • Python 3.9 or newer MUST be installed
  • pipx is recommended as an alternative to pip because it installs BBOT in its own Python environment.

If you need help with installation, please refer to the wiki.

Demo

subdomain demo

Scanning with BBOT

Note: the httpx module is needed in most scans because it is used by BBOT to visit webpages. For details, see the wiki.

Examples

# list modules
bbot -l

# subdomain enumeration
bbot --flags subdomain-enum --modules httpx --targets evilcorp.com

# passive only
bbot --flags passive --targets evilcorp.com

# web screenshots with gowitness
bbot -m naabu httpx gowitness --name my_scan --output-dir . -t evilcorp.com 1.2.3.4/28 4.3.2.1 targets.txt

# web spider (search for emails, etc.)
bbot -m httpx -c web_spider_distance=2 -t www.evilcorp.com

Using BBOT as a Python library

from bbot.scanner import Scanner

# this will prompt for a sudo password on first run
# if you prefer, you can export BBOT_SUDO_PASS instead
scan = Scanner("evilcorp.com", "1.2.3.0/24", modules=["naabu"], output_modules=["http"])

len(scan.target) # --> 257
"1.2.3.4" in scan.target # --> True
"4.3.2.1" in scan.target # --> False
"www.evilcorp.com" in scan.target # --> True

scan.start()

Output

BBOT outputs to STDOUT by default, but it can output in multiple formats simultaneously (with --output-module).

# tee to a file
bbot -f subdomain-enum -t evilcorp.com | tee evilcorp.txt

# output to JSON
bbot --output-module json -f subdomain-enum -t evilcorp.com | jq

# output to CSV, TXT, and JSON, in current directory
bbot -o . --output-module human csv json -f subdomain-enum -t evilcorp.com

For every scan, BBOT generates a unique and mildly-entertaining name like fuzzy_gandalf. Output for that scan, including the word cloud and any gowitness screenshots, etc., are saved to a folder by that name in ~/.bbot/scans. The most recent 20 scans are kept, and older ones are removed. You can change the location of BBOT's output with --output, and you can also pick a custom scan name with --name.

If you reuse a scan name, it will append to its original output files and leverage the previous word cloud.

Neo4j

Neo4j is the funnest (and prettiest) way to view and interact with BBOT data.

neo4j

  • You can get Neo4j up and running with a single docker command:
docker run -p 7687:7687 -p 7474:7474 --env NEO4J_AUTH=neo4j/bbotislife neo4j
  • After that, run bbot with --output-modules neo4j
bbot -f subdomain-enum -t evilcorp.com --output-modules human neo4j

Usage

$ bbot --help
usage: bbot [-h] [-t TARGET [TARGET ...]] [-w WHITELIST [WHITELIST ...]] [-b BLACKLIST [BLACKLIST ...]] [-s] [-n SCAN_NAME] [-m MODULE [MODULE ...]] [-l] [-em MODULE [MODULE ...]] [-f FLAG [FLAG ...]]
            [-rf FLAG [FLAG ...]] [-ef FLAG [FLAG ...]] [-om MODULE [MODULE ...]] [-o DIR] [-c [CONFIG ...]] [--allow-deadly] [-v] [-d] [--force] [-y] [--dry-run] [--current-config] [--save-wordcloud FILE]
            [--load-wordcloud FILE] [--no-deps | --force-deps | --retry-deps | --ignore-failed-deps] [-a]

Bighuge BLS OSINT Tool

options:
  -h, --help            show this help message and exit
  -n SCAN_NAME, --name SCAN_NAME
                        Name of scan (default: random)
  -m MODULE [MODULE ...], --modules MODULE [MODULE ...]
                        Modules to enable. Choices: affiliates,asn,aspnet_viewstate,azure_tenant,binaryedge,blind_ssrf,bypass403,c99,censys,certspotter,cookie_brute,crobat,crt,dnscommonsrv,dnsdumpster,dnszonetransfer,emailformat,ffuf,ffuf_shortnames,generic_ssrf,getparam_brute,github,gowitness,hackertarget,header_brute,host_header,httpx,hunt,hunterio,iis_shortnames,ipneighbor,leakix,massdns,naabu,ntlm,nuclei,passivetotal,pgp,securitytrails,shodan_dns,skymem,smuggler,sslcert,sublist3r,telerik,threatminer,urlscan,viewdns,wappalyzer,wayback,zoomeye
  -l, --list-modules    List available modules.
  -em MODULE [MODULE ...], --exclude-modules MODULE [MODULE ...]
                        Exclude these modules.
  -f FLAG [FLAG ...], --flags FLAG [FLAG ...]
                        Enable modules by flag. Choices: active,aggressive,brute-force,deadly,passive,portscan,report,safe,slow,subdomain-enum,web
  -rf FLAG [FLAG ...], --require-flags FLAG [FLAG ...]
                        Disable modules that don't have these flags (e.g. --require-flags passive)
  -ef FLAG [FLAG ...], --exclude-flags FLAG [FLAG ...]
                        Disable modules with these flags. (e.g. --exclude-flags brute-force)
  -om MODULE [MODULE ...], --output-modules MODULE [MODULE ...]
                        Output module(s). Choices: csv,http,human,json,neo4j,websocket
  -o DIR, --output-dir DIR
  -c [CONFIG ...], --config [CONFIG ...]
                        custom config file, or configuration options in key=value format: 'modules.shodan.api_key=1234'
  --allow-deadly        Enable running modules tagged as "deadly"
  -v, --verbose         Be more verbose
  -d, --debug           Enable debugging
  --force               Run scan even if module setups fail
  -y, --yes             Skip scan confirmation prompt
  --dry-run             Abort before executing scan
  --current-config      Show current config in YAML format

Target:
  -t TARGET [TARGET ...], --targets TARGET [TARGET ...]
                        Targets to seed the scan
  -w WHITELIST [WHITELIST ...], --whitelist WHITELIST [WHITELIST ...]
                        What's considered in-scope (by default it's the same as --targets)
  -b BLACKLIST [BLACKLIST ...], --blacklist BLACKLIST [BLACKLIST ...]
                        Don't touch these things
  -s, --strict-scope    Don't consider subdomains of target/whitelist to be in-scope

Word cloud:
  Save/load wordlist of common words gathered during a scan

  --save-wordcloud FILE
                        Output wordcloud to custom file when the scan completes
  --load-wordcloud FILE
                        Load wordcloud from a custom file

Module dependencies:
  Control how modules install their dependencies

  --no-deps             Don't install module dependencies
  --force-deps          Force install all module dependencies
  --retry-deps          Try again to install failed module dependencies
  --ignore-failed-deps  Run modules even if they have failed dependencies

Agent:
  Report back to a central server

  -a, --agent-mode      Start in agent mode

BBOT Config

BBOT loads its config from these places in the following order:

  • ~/.config/bbot/defaults.yml
  • ~/.config/bbot/bbot.yml <-- Use this one as your main config
  • ~/.config/bbot/secrets.yml <-- Use this one for sensitive stuff like API keys
  • command line (via --config)

Command-line arguments take precedence over all others. You can give BBOT a custom config file with --config myconf.yml, or individual arguments like this: --config http_proxy=http://127.0.0.1:8080 modules.shodan_dns.api_key=1234. To display the full and current BBOT config, including any command-line arguments, use bbot --current-config.

For explanations of config options, see defaults.yml or the wiki

Modules

ModuleNeeds API KeyDescriptionFlagsProduced Events
aspnet_viewstate Parse web pages for viewstates and check them against blacklist3ractive,safe,webVULNERABILITY
bypass403 Check 403 pages for common bypassesactive,aggressive,webFINDING
cookie_brute Check for common HTTP cookie parametersactive,aggressive,brute-force,slow,webFINDING
dnszonetransfer Attempt DNS zone transfersactive,safe,subdomain-enumDNS_NAME
ffuf A fast web fuzzer written in Goactive,aggressive,brute-force,deadly,webURL
ffuf_shortnames Use ffuf in combination IIS shortnamesactive,aggressive,brute-force,webURL
generic_ssrf Check for generic SSRFsactive,aggressive,webVULNERABILITY
getparam_brute Check for common HTTP GET parametersactive,aggressive,brute-force,slow,webFINDING
gowitness Take screenshots of webpagesactive,safe,webSCREENSHOT
header_brute Check for common HTTP header parametersactive,aggressive,brute-force,slow,webFINDING
host_header Try common HTTP Host header spoofing techniquesactive,aggressive,webFINDING
httpx Visit webpages. Many other modules rely on httpxactive,safe,webHTTP_RESPONSE,URL
hunt Watch for commonly-exploitable HTTP parametersactive,safe,webFINDING
iis_shortnames Check for IIS shortname vulnerabilityactive,safeURL_HINT
naabu Execute port scans with naabuactive,aggressive,portscanOPEN_TCP_PORT
ntlm Watch for HTTP endpoints that support NTLM authenticationactive,safe,webDNS_NAME,FINDING
nuclei Fast and customisable vulnerability scanneractive,aggressive,deadly,webVULNERABILITY
smuggler Check for HTTP smugglingactive,aggressive,brute-force,slow,webFINDING
sslcert Visit open ports and retrieve SSL certificatesactive,email-enum,safe,subdomain-enumDNS_NAME,EMAIL_ADDRESS
telerik Scan for critical Telerik vulnerabilitiesactive,aggressive,webFINDING,VULNERABILITY
vhost Fuzz for virtual hostsactive,aggressive,brute-force,deadly,slow,webDNS_NAME,VHOST
wappalyzer Extract technologies from web responsesactive,safe,webTECHNOLOGY
affiliates Summarize affiliate domains at the end of a scanpassive,report,safe 
asn Query bgpview.io for ASNspassive,report,safe,subdomain-enumASN
azure_tenant Query Azure for tenant sister domainspassive,safe,subdomain-enumDNS_NAME
binaryedgeXQuery the BinaryEdge APIpassive,safe,subdomain-enumDNS_NAME,EMAIL_ADDRESS,IP_ADDRESS,OPEN_PORT,PROTOCOL
c99XQuery the C99 API for subdomainspassive,safe,subdomain-enumDNS_NAME
censysXQuery the Censys APIemail-enum,passive,safe,subdomain-enumDNS_NAME,EMAIL_ADDRESS,IP_ADDRESS,OPEN_PORT,PROTOCOL
certspotter Query Certspotter's API for subdomainspassive,safe,subdomain-enumDNS_NAME
crobat Query Project Crobat for subdomainspassive,safe,subdomain-enumDNS_NAME
crt Query crt.sh (certificate transparency) for subdomainspassive,safe,subdomain-enumDNS_NAME
dnscommonsrv Check for common SRV recordspassive,safe,subdomain-enumDNS_NAME
dnsdumpster Query dnsdumpster for subdomainspassive,safe,subdomain-enumDNS_NAME
emailformat Query email-format.com for email addressesemail-enum,passive,safeEMAIL_ADDRESS
githubXQuery Github's API for related repositoriespassive,safe,subdomain-enumURL_UNVERIFIED
hackertarget Query the hackertarget.com API for subdomainspassive,safe,subdomain-enumDNS_NAME
hunterioXQuery hunter.io for emailsemail-enum,passive,safe,subdomain-enumDNS_NAME,EMAIL_ADDRESS,URL_UNVERIFIED
ipneighbor Look beside IPs in their surrounding subnetaggressive,passive,subdomain-enumIP_ADDRESS
leakix Query leakix.net for subdomainspassive,safe,subdomain-enumDNS_NAME
massdns Brute-force subdomains with massdns (highly effective)aggressive,brute-force,passive,slow,subdomain-enumDNS_NAME
passivetotalXQuery the PassiveTotal API for subdomainspassive,safe,subdomain-enumDNS_NAME
pgp Query common PGP servers for email addressesemail-enum,passive,safeEMAIL_ADDRESS
securitytrailsXQuery the SecurityTrails API for subdomainspassive,safe,subdomain-enumDNS_NAME
shodan_dnsXQuery Shodan for subdomainspassive,safe,subdomain-enumDNS_NAME
skymem Query skymem.info for email addressesemail-enum,passive,safeEMAIL_ADDRESS
sublist3r Query sublist3r's API for subdomainspassive,safe,subdomain-enumDNS_NAME
threatminer Query threatminer's API for subdomainspassive,safe,subdomain-enumDNS_NAME
urlscan Query urlscan.io for subdomainspassive,safe,subdomain-enumDNS_NAME,URL_UNVERIFIED
viewdns Query viewdns.info's reverse whois for related domainspassive,safe,subdomain-enumDNS_NAME
wayback Query archive.org's API for subdomainspassive,safe,subdomain-enumDNS_NAME,URL_UNVERIFIED
zoomeyeXQuery ZoomEye's API for subdomainspassive,safe,subdomain-enumDNS_NAME

Download details:

Author: blacklanternsecurity
Source code: https://github.com/blacklanternsecurity/bbot
License: GPL-3.0 license

#python #bot

BEE bot: OSINT Automation for Hackers Written in Python

Attobot: Julia Package Release Bot

AttoBot

NOTE: AttoBot has been disabled, please use Registrator.jl.

AttoBot is a package release bot for Julia. It creates pull requests to Julia METADATA when releases are tagged in GitHub, as an alternative to the PkgDev.jl functions register, tag and publish.

Usage

To set up AttoBot on your repository, go to https://github.com/integration/attobot and click "Configure" to select the repositories you wish to add. It will only operate on packages with the standard ".jl" suffix (all other packages will be ignored).

If the package is not yet registered in METADATA.jl, it will be automatically added when you make your first release.

Creating a release

Releases are created via GitHub releases: this is some extra functionality built on top of git tags that trigger a webhook used by AttoBot.

  1. Click on the "releases" link in the repository banner. 
    release link
  2. Click "Draft new release" 
    draft new release
  3. Enter a tag label in the appropriate semver form (i.e. vX.Y.Z where X,Y,Z are numbers): GitHub will create the tag if it doesn't already exist. Include any other details and click "Publish release".

AttoBot will then open a pull request against METADATA and CC you in the process. In certain cases AttoBot may open an issue on the repository if the release is not correct (e.g. if the tag is not in the correct form). If the pull request does not appear within 30 seconds or so, please open an issue.

Updating/deleting a release

If you need to make a change before the release before the METADATA pull request has been merged (e.g. if you need to fix your Compat settings), the easiest option is to delete the release (and corresponding tag), then create a new release with the same version number; AttoBot will then update the existing pull request and make a comment that it has been updated. To delete a release and its tag:

  1. Click on the "releases" link in the repository banner.
    release link
  2. Click on the title of the release in question
    release title
  3. Click "Delete".
    release delete
  4. The tag still exists; click on the tag title
    tag title
  5. Click "Delete"
    release title

Privacy statement

AttoBot receives the content of certain GitHub hooks, namely the integration_installation event (which doesn't appear to be documented, but in any case is ignored by AttoBot), and the release event. These contain certain publicly available details about the repository and the user who initiated the event. AttoBot will also make several subsequent queries via the public GitHub api to the repository in question. The contents of these may be retained in server logs.

The user who triggers the release will be marked as the commit author, and if their email is publicly available via GitHub, or they have made a commit to the repository in question using a public email address, then it will appear in the METADATA commit log. If you don't wish for this to happen, then you should make your email address private.

AttoBot should not be enabled on private repositories: not only are these not supported by METADATA (thus any such pull requests will be rejected), but you may inadvertently leak private information.

Credits

Download Details:

Author: Attobot
Source Code: https://github.com/attobot/attobot 
License: View license

#julia #bot 

Attobot: Julia Package Release Bot

Registrator.jl: Julia Package Registration Bot

Registrator  

Registrator is a GitHub app that automates creation of registration pull requests for your julia packages to the General registry. Install the app below!

"amelia robot logo"

How to Use

There are two ways to use Registrator: a web interface and a GitHub app.

Via the Web Interface

This workflow supports repositories hosted on either GitHub or GitLab.

Go to https://juliahub.com and log in using your GitHub or GitLab account. Then click on "Register packages" on the left menu. There are also more detailed instructions here.

Via the GitHub App

Unsurprisingly, this method only works for packages whose repositories are hosted on GitHub.

The procedure for registering a new package is the same as for releasing a new version.

If the registration bot is not added to the repository, @JuliaRegistrator register will not result in package registration.

  1. Click on the "install" button above to add the registration bot to your repository
  2. Set the (Julia)Project.toml version field in your repository to your new desired version.
  3. Comment @JuliaRegistrator register on the commit/branch you want to register (e.g. like here or here).
  4. If something is incorrect, adjust, and redo step 2.
  5. If the automatic tests pass, but a moderator makes suggestions (e.g., manually updating your (Julia)Project.toml to include a [compat] section with version requirements for dependencies), then incorporate suggestions as you see fit into a new commit, and redo step 2 for the new commit. You don't need to do anything to close out the old request.
  6. Finally, either rely on the TagBot GitHub Action to tag and make a github release or alternatively tag the release manually.

Registrator will look for the project file in the master branch by default, and will use the version set in the (Julia)Project.toml file via, for example, version = "0.1.0". To use a custom branch comment with:

@JuliaRegistrator register branch=name-of-your-branch

The old pseudo-Julia syntax is also still supported:

@JuliaRegistrator register(branch="foo")

Transitioning from REQUIRE to Project.toml

Download gen_project.jl, enter in your package directory and run julia gen_project.jl, resulting in a Project.toml file. You may need to do minor modifications (license, current version, description, etc.) and then remove the REQUIRE file, since it is only used for packages supporting Julia 0.6 and is otherwise irrelevant now.

Check that your package conforms to the required Project.toml structure found in the general package guidelines.

Details for triggering JuliaRegistrator (for step 2 above)

Either:

  1. Open an issue and add @JuliaRegistrator register as a comment. You can re-trigger the registrator by commenting @JuliaRegistrator register again (in case registrator reports an error or to make changes).
  2. Add a comment to a commit and say @JuliaRegistrator register.

Note: Only collaborators on the package repository and public members on the organization the package is under are allowed to register. If you are not a collaborator, you can request a collaborator trigger registrator in a GitHub issue or a comment on a commit.

If you want to register as a private member you should host your own instance of Registrator, see the documentation.

Release notes

If you have enabled TagBot on your repositories, then you may write your release notes in the same place that you trigger Registrator, or allow them to be automatically generated from closed issues and merged pull requests instead. These can later be edited via the GitHub releases interface.

To write your release notes, add a section labeled "Release notes:" or "Patch notes:" to your Registrator trigger issue/comment, after the @JuliaRegistrator trigger. For example,

@JuliaRegistrator register

Release notes:

Check out my new features!

Note that if you have not enabled TagBot, no release will be made at all, and so any release notes you write will not be used.

Note on git tags and GitHub releases

The Julia package manager does not rely on git tags and GitHub releases. However, Registrator will generate a git tag command for you to optionally create a corresponding tag with your package version, or you can use TagBot as is mentioned above.

Note on documentation build

The docs for your project will be automatically built by DocumentationGenerator.jl. Please see that repo for details. Your docs should show up at pkg.julialang.org/docs.

By default, docs/make.jl will be run to build the docs. If that is missing, the README.md will be used instead.

Registering a package in a subdirectory

If the package you want to register is in a subdirectory of your git repository, you can tell Registrator to register it by adding the subdir argument to your trigger, e.g. @JuliaRegistrator register subdir=path/to/my/package.

Approving pull requests on the registry

Pull requests that comply with the automatic merging guidelines will be merged without human intervention periodically. On other cases, a registry maintainer will manually merge the pull request made by Registrator.

Private packages and registries

Private packages will be ignored by the current running instance of Registrator. Please see the documentation on how to host your own Registrator for private packages.

Install Registrator:

install

Click on the "install" button above to add the registration bot to your repository

Download Details:

Author: JuliaComputing
Source Code: https://github.com/JuliaComputing/Registrator.jl 
License: View license

#julia #bot #registration 

Registrator.jl: Julia Package Registration Bot
Gordon  Taylor

Gordon Taylor

1660768440

Isbot: Detect Bots/crawlers/spiders using The User Agent String

isbot 🤖/👨‍

Detect bots/crawlers/spiders using the user agent string.

Usage

import isbot from 'isbot'

// Nodejs HTTP
isbot(request.getHeader('User-Agent'))

// ExpressJS
isbot(req.get('user-agent'))

// Browser
isbot(navigator.userAgent)

// User Agent string
isbot('Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)') // true
isbot('Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36') // false

Additional functionality

Extend: Add user agent patterns

Add rules to user agent match RegExp: Array of strings

isbot('Mozilla/5.0') // false
isbot.extend([
    'istat',
    '^mozilla/\\d\\.\\d$'
])
isbot('Mozilla/5.0') // true

Exclude: Remove matches of known crawlers

Remove rules to user agent match RegExp (see existing rules in src/list.json file)

isbot('Chrome-Lighthouse') // true
isbot.exclude(['chrome-lighthouse']) // pattern is case insensitive
isbot('Chrome-Lighthouse') // false

Find: Verbose result

Return the respective match for bot user agent rule

isbot.find('Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0 DejaClick/2.9.7.2') // 'DejaClick'

Matches: Get patterns

Return all patterns that match the user agent string

isbot.matches('Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0 SearchRobot/1.0') // ['bot', 'search']

Clear:

Remove all matching patterns so this user agent string will pass

const ua = 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0 SearchRobot/1.0';
isbot(ua) // true
isbot.clear(ua)
isbot(ua) // false

Spawn: Create new instances

Create new instances of isbot. Instance is spawned using spawner's list as base

const one = isbot.spawn()
const two = isbot.spawn()

two.exclude(['chrome-lighthouse'])
one('Chrome-Lighthouse') // true
two('Chrome-Lighthouse') // false

Create isbot using custom list (instead of the maintained list)

const lean = isbot.spawn([ 'bot' ])
lean('Googlebot') // true
lean('Chrome-Lighthouse') // false

Definitions

  • Bot. Autonomous program imitating or replacing some aspect of a human behaviour, performing repetitive tasks much faster than human users could.
  • Good bot. Automated programs who visit websites in order to collect useful information. Web crawlers, site scrapers, stress testers, preview builders and other programs are welcomed on most websites because they serve purposes of mutual benefits.
  • Bad bot. Programs which are designed to perform malicious actions, ultimately hurting businesses. Testing credential databases, DDoS attacks, spam bots.

Clarifications

What does "isbot" do?

This package aims to identify "Good bots". Those who voluntarily identify themselves by setting a unique, preferably descriptive, user agent, usually by setting a dedicated request header.

What doesn't "isbot" do?

It does not try to recognise malicious bots or programs disguising themselves as real users.

Why would I want to identify good bots?

Recognising good bots such as web crawlers is useful for multiple purposes. Although it is not recommended to serve different content to web crawlers like Googlebot, you can still elect to

  • Flag pageviews to consider with business analysis.
  • Prefer to serve cached content and relieve service load.
  • Omit third party solutions' code (tags, pixels) and reduce costs.

It is not recommended to whitelist requests for any reason based on user agent header only. Instead other methods of identification can be added such as reverse dns lookup.

Data sources

We use external data sources on top of our own lists to keep up to date

Crawlers user agents:

Non bot user agents:

Missing something? Please open an issue

Major releases breaking changes (full changelog)

Version 3

Remove testing for node 6 and 8

Version 2

Change return value for isbot: true instead of matched string

Version 1

No functional change

Real world data

| Execution times in milliseconds | - |

Download Details:

Author: Omrilotan
Source Code: https://github.com/omrilotan/isbot 
License: Unlicense license

#javascript #bot #crawler 

Isbot: Detect Bots/crawlers/spiders using The User Agent String
Python  Library

Python Library

1660297200

MultiBot: A Platform Agnostic High-level Bot Infrastructure on Python

MultiBot

Platform agnostic high-level bot infrastructure. Develop one bot and you will have three: one for Discord, another one for Telegram and another one for Twitch. All bots use the same objects and logic.

For now there are adapters for three platforms but more may be added in the future.

Installation

Python 3.10 or higher is required.

pip install multibot

Quick start

Discord

You will need create an discord application at https://discord.com/developers/applications and generate a BOT_TOKEN for your bot.

You will have to select the bot and applications.commands scopes and the Administrator permission. And as for the Discord Intents (in the Bot/Build-A-Bot panel) you must activate PRESENCE INTENT, SERVER MEMBERS INTENT and MESSAGE CONTENT INTENT.

import os

from multibot import DiscordBot, Message

discord_bot = DiscordBot(os.environ['DISCORD_BOT_TOKEN'])


@discord_bot.register('hello')
async def function_name_1(message: Message):
    await discord_bot.send('Hi!', message)


discord_bot.start()

Telegram

You will need your own API_ID and API_HASH. To get them see Native Telegram app & MTProto configuration.

The first time you start the bot you will need a BOT_TOKEN (then you can save and reuse the session). To get your BOT_TOKEN you will need to talk to BotFather.

Other configurations with BotFather:

  • Deactivate the privacy mode to read group messages or add your bot as an administrator.
  • Activate the inline mode if you want to use it.
import os

from multibot import Message, TelegramBot

telegram_bot = TelegramBot(
    api_id=os.environ['TELEGRAM_API_ID'],
    api_hash=os.environ['TELEGRAM_API_HASH'],
    bot_token=os.environ['TELEGRAM_BOT_TOKEN']
)


@telegram_bot.register('hello')
async def function_name_1(message: Message):
    await telegram_bot.send('Hi!', message)


telegram_bot.start()

The session will be saved locally using SQLite.

You can save the session data in a string (string session). This serves to facilitate the use of sessions when hosting the application in cloud services with ephemeral file systems:

from telethon.sessions import StringSession

...
string_session = StringSession.save(telegram_bot.bot_client.session)

If you have a string session you can provide it instead of the bot token:

telegram_bot = TelegramBot(
    api_id=os.environ['TELEGRAM_API_ID'],
    api_hash=os.environ['TELEGRAM_API_HASH'],
    bot_session=os.environ['TELEGRAM_BOT_SESSION']  # <----- instead of bot_token
)

Adding an user bot

You can add a user bot to your telegram bot to extend certain functionalities such as accessing the message history (useful if you have not been registering the messages in a database or similar), accessing the user's contacts to make whitelists, etc.

telegram_bot = TelegramBot(
    api_id=os.environ['TELEGRAM_API_ID'],
    api_hash=os.environ['TELEGRAM_API_HASH'],
    bot_session=os.environ['TELEGRAM_BOT_SESSION'],
    phone='+00123456789'
)

Or provide an user string session instead of phone:

telegram_bot = TelegramBot(
    api_id=os.environ['TELEGRAM_API_ID'],
    api_hash=os.environ['TELEGRAM_API_HASH'],
    bot_session=os.environ['TELEGRAM_BOT_SESSION'],
    user_session=os.environ['TELEGRAM_USER_SESSION'],
)

Twitch

You will need your own BOT_TOKEN which you can generate on: https://twitchapps.com/tmi/. For more information see https://dev.twitch.tv/docs/irc.

import os

from multibot import Message, TwitchBot

twitch_bot = TwitchBot(
    bot_token=os.environ['TWITCH_ACCESS_TOKEN'],
    initial_channels=['channel_name'],  # Optional. You can later make the bot join a chat with join() method
    owner_name='owner_name'  # Optional. So the bot knows who to respect. Although keep in mind that the streamer cannot be punished
)


@twitch_bot.register('hello')
async def function_name_1(message: Message):
    await twitch_bot.send('Hi!', message)


twitch_bot.start()

Run multiple bots

import asyncio
import os

from multibot import DiscordBot, TelegramBot, TwitchBot


async def main():
    discord_bot = DiscordBot(os.environ['DISCORD_BOT_TOKEN'])

    telegram_bot = TelegramBot(
        api_id=os.environ['TELEGRAM_API_ID'],
        api_hash=os.environ['TELEGRAM_API_HASH'],
        bot_token=os.environ['TELEGRAM_BOT_TOKEN']
    )

    # If you run a TwitchBot in an asyncio loop you must create it inside the loop like below.
    # Other bots like DiscordBot or TelegramBot don't have this need and can be created at the module level.
    twitch_bot = TwitchBot(
        bot_token=os.environ['TWITCH_ACCESS_TOKEN'],
        initial_channels=['channel_name'],
        owner_name='owner_name'
    )

    await asyncio.gather(
        discord_bot.start(),
        telegram_bot.start(),
        twitch_bot.start()
    )


asyncio.run(main())

Extended tutorial

How the bot works

The bot works by registering functions that will be executed later when the user provides an input message that meets the requirements specified in the arguments of Multibot.register().

Each function you have registered in the bot will receive a Message object that contains all the necessary information related to the context of said message.

multiBot_class_diagram

 

Ways to design your bot

For the examples we are going to use the TelegramBot. But remember that all bots work the same since they use the same objects and logic. "They speak the same language".

A) Simple form

import os
import random

import flanautils
from multibot import Message, TelegramBot

bot = TelegramBot(
    api_id=os.environ['TELEGRAM_API_ID'],
    api_hash=os.environ['TELEGRAM_API_HASH'],
    bot_token=os.environ['TELEGRAM_BOT_TOKEN']
)

@bot.register('hello')
async def function_name_1(message: Message):
    """
    This function will be executed when someone types something like "hello".

    Functions names are irrelevant.
    """

    await bot.send('Hi!', message)  # response in same chat of received message context


@bot.register('multibot', min_ratio=1)
async def function_name_2(message: Message):
    """
    This function will be executed when someone types exactly "multibot".

    min_ratio=0.93 by default.
    """

    await bot.delete_message(message)  # deletes the received message
    bot_message = await bot.send('Message deleted.', message)  # keep the response message

    await flanautils.do_later(10, bot.delete_message, bot_message)  # delete the response message after 10 seconds


@bot.register(('house', 'home'))
# @bot.register(['house', 'home'])  <-- same
# @bot.register('house home')       <-- same
async def function_name_3(message: Message):
    """This function will be executed when someone types "house" or/and "home"."""

    await bot.clear(5, message)  # delete last 5 message (only works if a user_bot is activated in current chat)


@bot.register((('hello', 'hi'), ('world',)))  # <-- note that is Iterable[Iterable[str]]
# @bot.register([('hello', 'hi'), ('world',)])  <-- same
# @bot.register(['hello hi', ['world']])        <-- same
# @bot.register(['hello hi', 'world'])          !!! NOT same, this is "or" logic (like previous case)
async def function_name_4(message: Message):
    """This function will be executed when someone types ("hello" or/and "hi") and "world"."""

    message.chat = await bot.get_chat('@user_name')  # get chat object from id or user_name and insert it to message context
    await bot.send('I <3 to kill you.', message)


@bot.register('troll')
async def function_name_5(message: Message):
    """This function will be executed when someone types "troll" but returns if he isn't an admin."""

    if not message.author.is_admin:
        return

    await bot.ban('@user_name', message)


@bot.register(always=True)
async def function_name_6(message: Message):
    """This function will be executed always but returns if bot isn't mentioned."""

    if not bot.is_bot_mentioned(message):
        return

    await bot.send('shut up.', message)


@bot.register(default=True)
async def function_name_7(message: Message):
    """
    This function will be executed if no other function is determined by provided keywords.

    always=True functions don't affect to determine if default=True functions are called.
    """

    phrases = ["I don't understand u mate", '?', '???????']
    await bot.send(random.choice(phrases), message)


bot.start()

B) Extensible form

import os
import random

import flanautils
from multibot import Message, TelegramBot, admin, bot_mentioned


class MyBot(TelegramBot):
    def __init__(self):
        super().__init__(api_id=os.environ['TELEGRAM_API_ID'],
                         api_hash=os.environ['TELEGRAM_API_HASH'],
                         bot_token=os.environ['TELEGRAM_BOT_TOKEN'])

    def _add_handlers(self):
        super()._add_handlers()
        self.register(self.function_name_1, 'hello')
        self.register(self.function_name_2, 'multibot', min_ratio=1)
        self.register(self.function_name_3, ('house', 'home'))
        self.register(self.function_name_4, (('hello', 'hi'), ('world',)))  # <-- note that is Iterable[Iterable[str]]
        self.register(self.function_name_5, 'troll')
        self.register(self.function_name_6, always=True)
        self.register(self.function_name_7, default=True)

    async def function_name_1(self, message: Message):
        """
        This function will be executed when someone types something like "hello".

        Functions names are irrelevant.
        """

        await self.send('Hi!', message)  # response in same chat of received message context

    async def function_name_2(self, message: Message):
        """
        This function will be executed when someone types exactly "multibot".

        min_ratio=0.93 by default.
        """

        await self.delete_message(message)  # deletes the received message
        bot_message = await self.send('Message deleted.', message)  # keep the response message

        await flanautils.do_later(10, self.delete_message, bot_message)  # delete the response message after 10 seconds

    async def function_name_3(self, message: Message):
        """This function will be executed when someone types "house" or/and "home"."""

        await self.clear(5, message)  # delete last 5 message (only works if a user_bot is activated in current chat)

    async def function_name_4(self, message: Message):
        """This function will be executed when someone types ("hello" or/and "hi") and "world"."""

        message.chat = await self.get_chat('@user_name')  # get chat object from id or user_name and insert it to message context
        await self.send('I <3 to kill you.', message)

    @admin
    async def function_name_5(self, message: Message):
        """This function will be executed when someone types "troll" but returns if he isn't an admin."""

        await self.ban('@user_name', message)

    @bot_mentioned
    async def function_name_6(self, message: Message):
        """This function will be executed always but returns if bot isn't mentioned."""

        await self.send('shut up.', message)

    async def function_name_7(self, message: Message):
        """
        This function will be executed if no other function is determined by provided keywords.

        always=True functions don't affect to determine if default=True functions are called.
        """

        phrases = ["I don't understand u mate", '?', '???????']
        await self.send(random.choice(phrases), message)


MyBot().start()

Annex

Native Telegram app & MTProto configuration

TelegramBot connects directly to Telegram servers using its own protocol (MTProto), so you are not limited by the http bots api. Anything you can do with the official mobile app, desktop or web is possible with this bot.

MTProto also allows the creation of user bots, bots that automate tasks with your own human account for which you would need to create a new session as when you open a session for the first time on a new device. Keep in mind that you will be asked for the security code that Telegram sends you by private chat when someone wants to log in with your account.

For both a normal bot and a user bot (bot using your "human" account) you will need the API_ID and API_HASH. To get them you will have to go to https://my.telegram.org, log in and create an app.

WARNING!

The my.telegram.org security code is NOT like a session code, do not give it to anyone, it is only to enter this website. If you have doubts: the code that MultiBot.TelegramBot may ask you for is NOT the same. MultiBot.TelegramBot would only need a different code in case of a new session when you run it for the first time.

my.telegram.org

Download details:

Author: AlberLC
Source code: https://github.com/AlberLC/multibot
License: MIT license

#python #bot

MultiBot: A Platform Agnostic High-level Bot Infrastructure on Python
Python  Library

Python Library

1660289820

Building a Messaging BOT for Whatsapp with Python

Whatsapp-messaging-BOT

A bot based on python compiled to a executable file for all Windows systems to send messages in bulk to recipients whose numbers need not be saved in your phone.

Steps to use

host the message in a text file in GitHub 6

Copy the url for the raw data 7

open the Folder 3

open the names.txt file and paste the list of names 4

open the numbers.txt file and paste the list of numbers 5

open the WhatsappBot.exe file and viola

 Pr Cut-1

Download details:

Author: akhilrajs
Source code: https://github.com/akhilrajs/Whatsapp-messaging-BOT
License: MIT license

#python #bot #whatsapp

Building a Messaging BOT for Whatsapp with Python
Lawson  Wehner

Lawson Wehner

1660254060

Autobot: A Command Line tool for Automating Common Developer Task

Autobot is a command-line templating engine for automating standardised repetitive operations, such as creating a new project with a specific folder structure or creating files and classes according to a predefined scheme to ensure compliance with architectural specifications. Autobot can also be used for configuring projects by creating build configurations both locally and in the CI.

Installation

Install Dart following these instructions.

Activate autobot running the following command:

$ dart pub global activate autobot

Check for the autobot version to see if autobot was successfully installed:

$ autobot version

Configuration

Autobot needs a .autobot_config.yaml file. Create a local or global one via the following commands:

# creates local config file in current working directory
$ autobot init
# creates local config file in given path (-p)
$ autobot init -p subfolder/subsubfolder/
# creates global config file in home directory
$ autobot init -g

This is a .autobot_config.yaml with all available configuration.

config:
  # tell autobot where is should search for tasks
  taskDir: some/relative_path/to_tasks_directory/

Tasks

Run an autobot task via the following command:

# assuming there is a my_task.yaml inside taskDir
$ autobot run --task my_task
# use -t instead of --task if you like short cuts :)

You can also omit run --task if you want:

$ autobot my_task

Autobot tasks are YAML files witch describe what needs to be done.

Pass flags to a task using : as prefix like so:

$ autobot my_task:first_flag:second_flag

Autobot assigns the flags to keys with the following schema flag<index>: This means that the first flag will be assigned to flag1, the second will be assigned to flag2 and so on.

You can add some meta data like name and description to a task like this:

meta:
  name: My task
  description: This is my autobot task

Use steps to define the actuall work like this:

meta:
  name: My task
  description: This is my autobot task

steps:
  - read:
    file: some/path/to/file.yaml

  - ask:
    key: name
    prompt: Whats your name?

  - ask:
    key: age
    prompt: How old are you?

  - write:
    file: some/path/output_file.txt
    content: My name is {{name}} and I'm {{age}} years old.

Available steps

Check out all available steps. Keep in mind that all fields of all steps (except vars) can be mustache templates for dynamic customization. Check out the Examples for more details.

ask

Asks the user for input and assigns that input to the key.

- ask:
  key: # String -> the key the value should be asssigned to
  prompt: # String -> the prompt to print

command

Runs a shell command.

- command:
  run: # String -> shell command

javascript

Runs a javascript. NOTE: Requires that node is installen in your commond line tool.

- javascript:
  run: # String -> javascript

read

Reads a yaml file. The data can then be used in other spets like write or javascript.

- read:
  file: # String -> path of yaml file

runTask

Runs a sub task.

- runTask:
  file: # String -> name of that which is loacted in taskDir of .autobot_config.yaml

vars

Define some data that can be used in other steps like write or javascript.

- vars:
  key: value # some key value pair
  dataArray: [a, b c] # some array
  dataMap:
    key: value
    key2: value2
  otherDataArray:
    - a
    - b
    - c
  someText: |
    Lorem ipsum...

write

Writes a file.

- write:

  # The path of the file which should be written
  file:

  # Whether writting is enabled or not.
  enabled: # n, no, false or y, yes, true

  # How the file should be written
  writeMethod: # keepExistingFile (default), replaceExistingFile, extendFile

  # Works only if writeMethod is extendFile
  extendAt: # Values: top, bottom, custom regex.

  # The content of the file
  content:

Environment

Autobot automatically reads all variables from the environment and provides them to all steps. This is very helpful if you want autobot to use variables from your CI or if you want integrate autobot into so existing processes or cli commands.

Autobot and CI

Since a CI doesn't support interactive scripts, autobot offers the possibility to set input values via arguments using -i or --input:

$ autobot run --task some_autobot_task --input userName=somename,userAge=23

This will skip the interactive command line prompt for all set values.

Examples

Javascript example

steps:
  - aks:
    key: userName
    prompt: What is your name?

  - ask:
    key: userAge
    prompt: How old are you?

  - javascript:
    run: |
      // Access the value of userName
      var userName = autobot.variables.userName
      // Check whether userName is blank. If yes, set a fallback value.
      if (!userName || userName.length === 0) {
        autobot.variables.userName = 'Some fallback name'
      }
      // Define a new variable
      autobot.variables.varFormJs = 'Hello!'

  - write:
    file: some/relative/path.txt
    content: Hi {{userName}}

  - write:
    file: /some/non_relative/path.txt
    content: |
      Hi {{userName}},
      is it true that you are {{userAge}} years old?
      This is a value from javascript: {{varFormJs}}

This example task ask the user for his name and age and will create two files. The first file will be $pwd/some/relative/path.txt with the following content:

Hi Peter

The second file will be /some/non_relative/path.txt with the following content:

Hi Peter,
is it true that you are 30 years old?
This is a value from javascript: Hello!

Read example

Assuming there is a yaml file like this on your machine called task_data.yaml:

key1: value1
key2: value2

varMap:
  mapKey1: mapValue1
  mapKey2: mapValue2

varList:
  - key: a
  - key: b
  - key: c

The task:

steps:
  - read:
    file: task_data.yaml

  - write:
    file: output.txt
    content: |
      Pairs: {{key1}}, {{key2}}
      Map pairs: {{varMap.mapKey1}} {{varMap.mapKey2}}
      List:
      {{#varList}}
        -> {{key}} <-
      {{/varList}}

Tis task will read the task_data.yaml and create the following file:

Pairs: value1, value2
Map pairs: mapValue1 mapValue2
List:
  -> a <-
  -> b <-
  -> c <-

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate autobot

Use it

The package has the following executables:

$ autobot

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add autobot

With Flutter:

 $ flutter pub add autobot

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  autobot: ^0.6.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:autobot/autobot.dart';

Download Details:

Author: DeveloperZoneIO
Source Code: https://github.com/DeveloperZoneIO/autobot 
License: MIT license

#flutter #dart #bot 

Autobot: A Command Line tool for Automating Common Developer Task
Reid  Rohan

Reid Rohan

1660115880

Bun-discord-bot: Official Discord Bot for Bun Server

Bun discord bot

Official serverless discord bot for bun discord server

Contributing tags

To create a new tag, you need to fork this repository and edit tags.toml file

Format:

[example-tag]
keywords = ["example", "tag"]
content = """
I love bun ❤️
"""

Informations:

Download Details:

Author: xHyroM
Source Code: https://github.com/xHyroM/bun-discord-bot 
License: MIT license

#typescript #bot #discord #server 

Bun-discord-bot: Official Discord Bot for Bun Server
Reid  Rohan

Reid Rohan

1660108500

Bun-discord-bot: An interaction Discord Bot Written in JS & TS

Bun Discord Bot

An interaction Discord bot written in JS and TS using Bun runtime environment. Contains simple get avatar and get user info commands. Starting up the bot only takes 0.02-0.05 ms.

This bot is created with Bun runtime

Using Bun runtime. Please visit their website on how to setup Bun runtime.

Getting Started

Cloning the repo

git clone https://github.com/MiraBellierr/bun-discord-bot

Development

To run this locally, rename .env.example to .env and fill in the variables, then you can run bun run.js to start a local dev environment and use something like ngrok/cloudflare to tunnel it to a URL.

Using ngrok

A way to expose a localhost port to a URL is by using ngrok. download

First, download and install ngrok, then type ngrok http 1337 in a new terminal. This will create a https://*.ngrok.io URL.

To instruct discord to use your server for all user-created interactions, you must:

  • Go to to Discord Developers Portal Applications Page.
  • Select / Create a new application. On the application's page, fill the "Interactions endpoint URL" input with the https://*.ngrok.io/interactions url.
  • Invite your application to your server using this URL: https://discord.com/oauth2/authorize?client_id=[client-id]&scope=applications.commands
  • You're ready to go!

Be aware that the ngrok URL expires after 2 hours, you'll have to restart the ngrok command after this delay.

Download Details:

Author: MiraBellierr
Source Code: https://github.com/MiraBellierr/bun-discord-bot 

#javascript #typescript #discord #bot 

Bun-discord-bot: An interaction Discord Bot Written in JS & TS
Brook  Hudson

Brook Hudson

1659196020

A Ruby Gem That Detects Bots, Spiders, Crawlers and Replicants.

Voight-Kampff

Voight-Kampff relies on a user agent list for its detection. It can easily tell you if a request is coming from a crawler, spider or bot. This can be especially helpful in analytics such as page hit tracking.

Installation

gem install voight_kampff

Configuration

A JSON file is used to match user agent strings to a list of known bots.

If you'd like to use an updated list or make your own customizations, run rake voight_kampff:import_user_agents. This will download a crawler-user-agents.json file into the ./config directory.

Note: The pattern entries in the JSON file are evaluated as regular expressions.

Usage

There are three ways to use Voight-Kampff

Through Rack::Request such as in your Ruby on Rails controllers:
request.bot?

Through the VoightKampff module:
VoightKampff.bot? 'your user agent string'

Through a VoightKampff::Test instance:
VoightKampff::Test.new('your user agent string').bot?

All of the above examples accept human? and bot? methods. All of these methods will return true or false.

Upgrading to version 1.0

Version 1.0 uses a new source for a list of bot user agent strings since the old source was no longer maintained. This new source, unfortuately, does not include as much detail. Therefore the following methods have been deprecated:

  • #browser?
  • #checker?
  • #downloader?
  • #proxy?
  • #crawler?
  • #spam?

In general the #bot? command tends to include all of these and I'm sure it's unlikely that anybody was getting this granular with their bot checking. So I see it as a small price to pay for an open and up to date bot list.

Also, the gem no longer extends ActionDispatch::Request instead it extends Rack::Request which ActionDispatch::Request inherits from. This allows the same functionality for Rails while opening the gem up to other rack-based projects.

FAQ

Q: What's with the name?
A: It's the machine in Blade Runner that is used to test whether someone is a human or a replicant.

Q: I've found a bot that isn't being matched
A: The list is being pulled from github.com/monperrus/crawler-user-agents. If you'd like to have entries added to the list, please create a pull request with that project. Once that pull request is merged, feel free to create an issue here and I'll release a new gem version with the updated list. In the meantime you can always run rake voight_kampff:import_user_agents on your project to get that updated list.

Q: __Why don't you use the user agent list from ______________ If you know of a better source for a list of bot user agent strings, please create an issue and let me know. I'm open to switching to a better source or supporting multiple sources. There are others out there but I like the openness of monperrus' list.

Thanks

Thanks to github.com/monperrus/crawler-user-agents for providing an open and easily updatable list of bot user agents.

Contributing

PR without tests will not get merged, Make sure you write tests for api and rails app. Feel free to ask for help, if you do not know how to write a determined test.

Running Tests?

  • bundle install
  • bundle exec rspec

Author: biola
Source code: https://github.com/biola/Voight-Kampff
License: MIT license

#ruby #ruby-on-rails 

A Ruby Gem That Detects Bots, Spiders, Crawlers and Replicants.