~kmdodrill/telegram-welcome-bot

69c347db03b2d1ef56718e640889219c778f3112 — Kenneth Dodrill 5 months ago master
Add all files from GitHub
A  => .github/CODE_OF_CONDUCT.md +38 -0
@@ 1,38 @@
# Code of Conduct

> A code of conduct is a set of rules outlining the social norms and rules and responsibilities of, or proper practices for, an individual, party or organization

## Summary

Sexual language and imagery is not appropriate for any communication and/or talks. Be kind and do not insult or put down others. Behave professionally. Remember that harassment and sexist, racist, or exclusionary jokes are not appropriate for this repository.
These are the values to which people in this community should aspire:

- Be friendly and welcoming
- Be patient
  - Remember that people have varying communication styles and that not everyone is using their native language. (Meaning and tone can be lost in translation.)
- Be thoughtful
  - Productive communication requires effort. Think about how your words will be interpreted.
  - Remember that sometimes it is best to refrain entirely from commenting.
- Be respectful
  - In particular, respect differences of opinion.
- Be charitable
  - Interpret the arguments of others in good faith, do not seek to disagree.
  - When we do disagree, try to understand why.
- Avoid destructive behavior:
  - Derailing: stay on topic; if you want to talk about something else, start a new conversation.
  - Unconstructive criticism: don't merely decry the current state of affairs; offer—or at least solicit—suggestions as to how things may be improved.
  - Snarking (pithy, unproductive, sniping comments)
  - Discussing potentially offensive or sensitive issues; this all too often leads to unnecessary conflict.
  - Microaggressions: brief and commonplace verbal, behavioral and environmental indignities that communicate hostile, derogatory or negative slights and insults to a person or group.

People are complicated. You should expect to be misunderstood and to misunderstand others; when this inevitably occurs, resist the urge to be defensive or assign blame. Try not to take offense where no offense was intended. Give people the benefit of the doubt. Even if the intent was to provoke, do not rise to it. It is the responsibility of all parties to de-escalate conflict when it arises.

## Reporting an incident

Incidents that violate the Code of Conduct are extremely damaging to this community, and they will not be tolerated. The silver lining is that, in many cases, these incidents present a chance for the offenders, and the teams at large, to grow, learn, and become better.

If you feel you have been treated unfairly, please let me (Kenneth Dodrill) know.

## Attribution

This Code of Conduct was adapted from both [Golang](https://golang.org/conduct) and the [Golang UK Conference](http://golanguk.com/conduct/).

A  => .github/CONTRIBUTING.md +34 -0
@@ 1,34 @@
# Contributing

I love contributions from everyone.
By participating in this project,
you agree to abide by the [code of conduct].

  [code of conduct]: https://github.com/kedodrill/telegram-welcome-bot/blobs/master/.github/CODE_OF_CONDUCT.md

I expect everyone to follow the code of conduct
anywhere in this project's codebase.

## Contributing Code

Make sure you have the proper dependencies:

- Rust
- Cargo

Fork the repo.

Set up the project

```bash
cargo build
```

Make your change. Push to your fork. Write a [good commit message][commit]. Submit a pull request.

  [commit]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html

Others will give constructive feedback.
This is a time for discussion and improvements,
and making the necessary changes will be required before we can
merge the contribution.

A  => .github/ISSUE_TEMPLATE/bug_report.md +32 -0
@@ 1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

# Bug Report

## Describe the bug
A clear and concise description of what the bug is.

## To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

## Expected behavior
A clear and concise description of what you expected to happen.

## Screenshots
If applicable, add screenshots to help explain your problem.

## Desktop (please complete the following information):
 - OS: [e.g. Fedora Linux / Windows 10]

## Additional context
Add any other context about the problem here.

A  => .github/ISSUE_TEMPLATE/feature_request.md +20 -0
@@ 1,20 @@
---
name: Feature Request
about: Suggest an idea for this project

---

# Feature Request

## I confirm:
- [ ] that I haven't found another request for this feature.
- [ ] that I have checked whether there are updates for my system available that
      contain this feature already.

## Description <!-- What do you want to be added? -->

## Justification [optional]

## Risks [optional]

## References [optional] <!-- Which issues are related? -->

A  => .gitignore +16 -0
@@ 1,16 @@
# Generated by Cargo
# will have compiled files and executables
/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# Ignore config file.
Settings.toml

# Ignore Blake's VS folder
.vs/
\ No newline at end of file

A  => .travis.yml +26 -0
@@ 1,26 @@
language: rust
os:
- linux
- osx
rust:
- stable
- beta
- nightly
services:
- docker
jobs:
  allow_failures:
  - rust: nightly
  fast_finish: true
before_deploy: "./build-release telegram-welcome-bot ${TRAVIS_TAG}-${TRAVIS_OS_NAME}"
deploy:
  provider: releases
  edge: true
  file_glob: true
  file: telegram-welcome-bot-${TRAVIS_TAG}-${TRAVIS_OS_NAME}.*
  on:
    repo: kedodrill/telegram-welcome-bot
    rust: stable
    tags: true
  token:
    secure: $GITHUB_TOKEN

A  => Cargo.toml +18 -0
@@ 1,18 @@
[package]
name = "telegram-welcome-bot"
version = "0.1.3"
authors = [
	"Kenneth Dodrill <kmdodrill@protonmail.com>",
	"Blake Burgess <blake.e.burgess@gmail.com>"
]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.7"
config = "0.9"
futures = "0.3"
openssl-probe = "0.1.2"
tokio = { version = "0.2", features = ["full"] }
telegram-bot = { git = 'https://github.com/telegram-rs/telegram-bot' }

A  => Dockerfile +7 -0
@@ 1,7 @@
FROM ekidd/rust-musl-builder

# We need to add the source code to the image because `rust-musl-builder`
# assumes a UID of 1000, but TravisCI has switched to 2000.
ADD --chown=rust:rust . ./

CMD cargo build --release

A  => LICENSE +21 -0
@@ 1,21 @@
MIT License

Copyright (c) 2020 Kenneth Dodrill

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

A  => README.md +48 -0
@@ 1,48 @@
[![Build Status](https://img.shields.io/travis/com/kedodrill/telegram-welcome-bot/master.svg)](https://travis-ci.com/kedodrill/telegram-welcome-bot)

# Telegram Welcome Bot
Telegram bot that welcomes new users (uses welcome messages from Discord), written in Rust.

Built with [telegram-rs/telegram-bot], discord messages copied over from [fourjr/Discord Join Messages].

[telegram-rs/telegram-bot]: https://github.com/telegram-rs/telegram-bot
[fourjr/Discord Join Messages]: https://gist.github.com/fourjr/0f47ce8a000c29cd4e24f8aeb7edd8e0

## Install

Go grab the latest [release], and decompress it.

[release]: https://github.com/kedodrill/telegram-welcome-bot/releases

## Usage

Directly after installation, please copy the `Settings.example.toml` over to `Settings.toml` like so:

```bash
cp Settings.example.toml Settings.toml
```

Now use a text editor of some sort to edit the file and set the values:

```bash
vi Settings.toml
```

The `TELEGRAM_BOT_TOKEN` is the token you receive after making your bot through BotFather.

Once you have the bot configured, just run the binary and the bot will be live!

## Adding more messages

Feel free to add more messages! To add more, go into the `data` folder in your installation. Here, you will find `Discord_Welcome_Messages.toml`. You can add (or remove!) keys and values here, but be sure that the numbers line up correctly:

```TOML
DISCORD_WELCOME_MESSAGE_1=""
DISCORD_WELCOME_MESSAGE_2=""
DISCORD_WELCOME_MESSAGE_3=""
# There's no 4 here!
DISCORD_WELCOME_MESSAGE_5=""
DISCORD_WELCOME_MESSAGE_6=""
```

The above example may result in an error, because this bot randomly generates a number and uses it to choose a welcome message.

A  => Settings.example.toml +1 -0
@@ 1,1 @@
TELEGRAM_BOT_TOKEN=""

A  => build-release +34 -0
@@ 1,34 @@
#!/bin/bash
#
# Usage: ./build-release <PROJECT> ${TRAVIS_TAG}-${TRAVIS_OS_NAME}
#
# The latest version of this script is available at
# https://github.com/emk/rust-musl-builder/blob/master/examples/build-release
#
# Called by `.travis.yml` to build release binaries.  We use
# ekidd/rust-musl-builder to make the Linux binaries so that we can run
# them unchanged on any distro, including tiny distros like Alpine (which
# is heavily used for Docker containers).  Other platforms get regular
# binaries, which will generally be dynamically linked against libc.
#
# If you have a platform which supports static linking of libc, and this
# would be generally useful, please feel free to submit patches.

set -euo pipefail

case `uname -s` in
    Linux)
        echo "Building static binaries using ekidd/rust-musl-builder"
        docker build -t build-"$1"-image .
        docker run -it --name build-"$1" build-"$1"-image
        docker cp build-"$1":/home/rust/src/target/x86_64-unknown-linux-musl/release/"$1" "$1"
        docker rm build-"$1"
        docker rmi build-"$1"-image
        zip "$1"-"$2".zip "$1"
        ;;
    *)
        echo "Building standard release binaries"
        cargo build --release
        zip -j "$1"-"$2".zip target/release/"$1"
        ;;
esac
\ No newline at end of file

A  => data/Discord_Welcome_Messages.toml +38 -0
@@ 1,38 @@
DISCORD_WELCOME_MESSAGE_1="{username} just joined the server - glhf!"
DISCORD_WELCOME_MESSAGE_2="{username} just joined. Everyone, look busy!"
DISCORD_WELCOME_MESSAGE_3="{username} just joined. Can I get a heal?"
DISCORD_WELCOME_MESSAGE_4="{username} joined your party."
DISCORD_WELCOME_MESSAGE_5="{username} joined. You must construct additional pylons."
DISCORD_WELCOME_MESSAGE_6="Ermagherd. {username} is here."
DISCORD_WELCOME_MESSAGE_7="Welcome, {username}. Stay awhile and listen."
DISCORD_WELCOME_MESSAGE_8="Welcome, {username}. We were expecting you ( ͡° ͜ʖ ͡°)"
DISCORD_WELCOME_MESSAGE_9="Welcome, {username}. We hope you brought pizza."
DISCORD_WELCOME_MESSAGE_10="Welcome {username}. Leave your weapons by the door."
DISCORD_WELCOME_MESSAGE_11="A wild {username} appeared."
DISCORD_WELCOME_MESSAGE_12="Swoooosh. {username} just landed."
DISCORD_WELCOME_MESSAGE_13="Brace yourselves. {username} just joined the server."
DISCORD_WELCOME_MESSAGE_14="{username} just joined. Hide your bananas."
DISCORD_WELCOME_MESSAGE_15="{username} just arrived. Seems OP - please nerf."
DISCORD_WELCOME_MESSAGE_16="{username} just slid into the server."
DISCORD_WELCOME_MESSAGE_17="A {username} has spawned in the server."
DISCORD_WELCOME_MESSAGE_18="Big {username} showed up!"
DISCORD_WELCOME_MESSAGE_19="Where’s {username}? In the server!"
DISCORD_WELCOME_MESSAGE_20="{username} hopped into the server. Kangaroo!!"
DISCORD_WELCOME_MESSAGE_21="{username} just showed up. Hold my beer."
DISCORD_WELCOME_MESSAGE_22="Challenger approaching - {username} has appeared!"
DISCORD_WELCOME_MESSAGE_23="It's a bird! It's a plane! Nevermind, it's just {username}."
DISCORD_WELCOME_MESSAGE_24="It's {username}! Praise the sun! \\\\[T]/"
DISCORD_WELCOME_MESSAGE_25="Never gonna give {username} up. Never gonna let {username} down."
DISCORD_WELCOME_MESSAGE_26="Ha! {username} has joined! You activated my trap card!"
DISCORD_WELCOME_MESSAGE_27="Roses are red, violets are blue, {username} joined this server with you."
DISCORD_WELCOME_MESSAGE_28="Hey! Listen! {username} has joined!"
DISCORD_WELCOME_MESSAGE_29="We've been expecting you, {username}."
DISCORD_WELCOME_MESSAGE_30="It's dangerous to go alone, take {username}!"
DISCORD_WELCOME_MESSAGE_31="{username} has joined the server! It's super effective!"
DISCORD_WELCOME_MESSAGE_32="Cheers, love! {username} is here!"
DISCORD_WELCOME_MESSAGE_33="{username} is here, as the prophecy foretold."
DISCORD_WELCOME_MESSAGE_34="{username} has arrived. Party's over."
DISCORD_WELCOME_MESSAGE_35="Ready player {username}."
DISCORD_WELCOME_MESSAGE_36="{username} is here to kick butt and chew bubblegum. And {username} is all out of gum."
DISCORD_WELCOME_MESSAGE_37="Hello. Is it {username} you're looking for?"
DISCORD_WELCOME_MESSAGE_38="{username} has joined. Stay a while and listen!"

A  => src/main.rs +71 -0
@@ 1,71 @@
extern crate rand;
extern crate config;
extern crate openssl_probe;

use config::*;
use telegram_bot::*;
use std::path::Path;
use futures::StreamExt;
use rand::distributions::{Distribution, Uniform};

async fn process(api: Api, message: Message, messages: &config::Config) -> Result<(), Error> {
    // If there are new chat members...
    if let MessageKind::NewChatMembers { ref data, .. } = message.kind {
        // Instantiate the random number generator.
        let mut rng = rand::thread_rng();

        // Get a random number (range is 1 to the total amount of messages in Discord_Welcome_Messages.toml).
        let range = Uniform::from(1..messages.collect().unwrap().len());
        let num = range.sample(&mut rng);

        // Use the random number to get a welcome message.
        let mut welcome_message_string: String = "DISCORD_WELCOME_MESSAGE_".to_owned();
        welcome_message_string.push_str(&num.to_string());

        let mut welcome_message: String = messages.get(&welcome_message_string)
            .expect("Unable to get a welcome message.");

        // Get the username from data.
        let username = data[0].username.as_deref().unwrap_or("New user");
		
		// Replace {username} in welcome_message with username.
        welcome_message = str::replace(&welcome_message, "{username}", username);
        
        api.send(message.text_reply(welcome_message)).await?;
    }

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    openssl_probe::init_ssl_cert_env_vars();
    
	// Set up our Config.
	let mut settings = Config::default();
    let mut messages = Config::default();
    settings
        // Add in `./Settings.toml`.
        .merge(config::File::with_name("Settings")).unwrap();
    messages
        // Add the discord welcome messages.
        .merge(config::File::from(Path::new("data/Discord_Welcome_Messages.toml"))).unwrap();

    // Set the token to the config value (still expect a value).
    let token: String = settings.get("TELEGRAM_BOT_TOKEN")
		.expect("TELEGRAM_BOT_TOKEN is not set. Please set it in `Settings.toml`.");

    // Initialize connection to the telegram api.
    let api = Api::new(token);
    let mut stream = api.stream();

    // Fetch new updates via long poll method
    while let Some(update) = stream.next().await {
        let update = update?;
        if let UpdateKind::Message(message) = update.kind {
            process(api.clone(), message, &messages).await?
        }
    }

    Ok(())
}