Skip to content
This repository has been archived by the owner on Sep 8, 2023. It is now read-only.

Commit

Permalink
Version 0.7.0 (#29)
Browse files Browse the repository at this point in the history
* Implement basic functionality without any additional features (#2)

Implementation of issue #1 

* Create basic Discord bot structure

* Run go dep init command

* Implement basic funtionality without any additional features

* Add package documentation file to package discorddnsbot

* Move send statements and enhance appearance (#6)

* Change command system and restructure DNS request code (#8)

* Implement modular mention system

* Restructure code and enhance embed appearance

* Enhance syntax embed message

* Change name to discord1111resolver (#9)

* Rename package to discord1111resolver

* Update README file

* Add Makefile and move main folder (#10)

* Change main folder name and add Makefile fields to main.go

* Add Makefile

* Add error message if not DNS record could be found (#12)

* Add error message if the requested DNS record could not be found

* Wrap DNS record not found message with upper statement

* Fix import path and vendor folder (#15)

* Fix import path in main.go

* Run godep ensure command

* Usage of supported DNS over TLS (#16)

* Change exit output in main file

* Implement usage of DNS over TLS

* Add extended messages and restructure command execution (#20)

* Adjust param split comments

* Restructure command handle system and add extended description

* Move messages to constants

* Fix description send action and beautify error format

* Implement discordbots.org integration (#21)

* Add discordbots.org token flag

* Implement discordbots.org status update

* Add discordbots.org update hook

* Change channel send instance to empty struct

* Fix discordbots.org API url and http.Request embedding

* Punycode domain resolving (#24)

* Implement punycode domain resolving

* Update format and fix another bug

- run gofmt command
- fix shutdown bug with channel send
- update embed format

* Add travis-ci file (#25)

* Adjust formatting, README file and add debug messages (#26)

* Add -level parameter for main application

* Add debug messages to main file

* Add debug messages to pkg package

* Add doc.go file to root project

* Update package name in doc file

* Change root package name

* Update package documentation

* Fix goreportcard issues

* Update README file

* Update version in Makefile (#28)
  • Loading branch information
mmichaelb committed Apr 20, 2018
1 parent 324cfb4 commit fc7411d
Show file tree
Hide file tree
Showing 732 changed files with 350,899 additions and 2 deletions.
10 changes: 10 additions & 0 deletions .travis.yml
@@ -0,0 +1,10 @@
language: go

go:
- 1.8.x
- 1.9.x
- 1.10.x

script:
- make build
- make install
89 changes: 89 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 38 additions & 0 deletions Gopkg.toml
@@ -0,0 +1,38 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true


[[constraint]]
name = "github.com/bwmarrin/discordgo"
version = "0.18.0"

[[constraint]]
name = "github.com/sirupsen/logrus"
version = "1.0.5"

[prune]
go-tests = true
unused-packages = true
14 changes: 14 additions & 0 deletions Makefile
@@ -0,0 +1,14 @@
APPLICATION_NAME = discord1111resolver
VERSION = 0.7.0
BRANCH = $(shell git rev-parse --abbrev-ref HEAD)
COMMIT = $(shell git rev-parse HEAD)

LD_FLAGS = -X "main.applicationName=${APPLICATION_NAME}" -X "main.version=${VERSION}" -X "main.branch=${BRANCH}" -X "main.commit=${COMMIT}"

# builds and formats the project with the built-in Golang tool
build:
@go build -ldflags '${LD_FLAGS}' ./cmd/discord1111resolver

# installs and formats the project with the built-in Golang tool
install:
@go install -ldflags '${LD_FLAGS}' ./cmd/discord1111resolver
30 changes: 28 additions & 2 deletions README.md
@@ -1,2 +1,28 @@
# discorddnsbot
This bot is written for fun only and returns DNS queries on request.
![1.1.1.1 DNS service](https://i.imgur.com/69fFwN9.png)
# discord1111resolver (1111Resolver) [![Discord Bots](https://discordbots.org/api/widget/status/432969981366501396.svg)](https://discordbots.org/bot/432969981366501396) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![stability-beta](https://img.shields.io/badge/stability-beta-33bbff.svg)](https://github.com/mkenney/software-guides/blob/master/STABILITY-BADGES.md#beta) [![GoDoc](https://godoc.org/github.com/mmichaelb/discord1111resolver?status.svg)](https://godoc.org/github.com/mmichaelb/discord1111resolver) [![Go Report Card](https://goreportcard.com/badge/github.com/mmichaelb/discord1111resolver)](https://goreportcard.com/report/github.com/mmichaelb/discord1111resolver)
Discord bot written for fun that returns DNS queries from the 1.1.1.1 DNS service. The structure is oriented to the
[Twitter 1111Resolver bot](https://twitter.com/1111Resolver).

## 1.1.1.1
Cloudflare and APNIC provide a fast and reliable DNS service. It is not only (one of) the fastest DNS services, but also
attaches great importance to privacy. For more information, please visit [https://1.1.1.1/](https://1.1.1.1/).

## Server integration
If you are a Discord server owner and want to integrate the 1111Resolver you can checkout the discordbots.org site. The
site provides an invite link as well as a status panel:

[![Discord Bots](https://discordbots.org/api/widget/432969981366501396.svg)](https://discordbots.org/bot/432969981366501396)

## Usage
As said before, this bot does not have much functionality yet but feel free to suggest new features by opening an issue
at the [issues tab](https://github.com/mmichaelb/discord1111resolver/issues). The basic functionality can be described
as follows:
```
@1111Resolver <A|AAAA|CNAME> <domain name>
```
An example of the usage would be:
```
@1111Resolver AAAA discordbots.org
```

*Please note that this bot is not associated with Cloudflare or APNIC.*
163 changes: 163 additions & 0 deletions cmd/discord1111resolver/main.go
@@ -0,0 +1,163 @@
package main

import (
"bytes"
"encoding/json"
"flag"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/miekg/dns"
"github.com/mmichaelb/discord1111resolver/pkg"
"github.com/sirupsen/logrus"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

var discordbotsUpdateURL = "https://discordbots.org/api/bots/%s/stats"

var applicationName, version, branch, commit string

var discordToken string
var discordbotsToken string
var discordbotsUpdateInterval time.Duration
var stringLevel string

func main() {
logrus.WithField("name", applicationName).WithField("version", version).WithField("branch", branch).WithField("commit", commit).Print("starting application...")
flag.StringVar(&stringLevel, "level", "info", "The logging level which should be used for log outputs.")
flag.StringVar(&discordToken, "token", "", "The Discord Bot token which should be used to authenticate with the Discord API.")
flag.StringVar(&discordbotsToken, "discordbotstoken", "", "The discordbots.org token which is used to update the bot's stats.")
flag.DurationVar(&discordbotsUpdateInterval, "discordbotsinterval", time.Minute*30, "The interval in which an update is sent to the discordbots.org API.")
flag.Parse()
// parse level from user input
level, err := logrus.ParseLevel(stringLevel)
if err != nil {
logrus.WithError(err).WithField("user-level", stringLevel).Fatal("could not find level")
}
// set logrus level
logrus.SetLevel(level)
// check if a discord API token is available
if discordToken == "" {
logrus.Warn("no Discord API token provided")
flag.PrintDefaults()
os.Exit(1)
}
logrus.Debug("connecting to Discord API...")
session, err := discordgo.New(fmt.Sprintf("Bot %v", discordToken))
if err != nil {
logrus.WithError(err).Fatal("could not connect to Discord API")
}
logrus.Debug("opening Discord session...")
if err := session.Open(); err != nil {
logrus.WithError(err).Fatal("could not open Discord session")
}
logrus.Debug("resolving information about the bot instance...")
user, err := session.User("@me")
if err != nil {
logrus.WithError(err).Fatal("could not get information about bot user")
}
logrus.Debug("checking if discordbots.org token is provided and whether continuous updates should be sent...")
// check if a discordbots.org API token is available
var discordbotsUpdateExitChan chan interface{}
if discordbotsToken != "" {
discordbotsUpdateExitChan = make(chan interface{})
discordbotsUpdateURL = fmt.Sprintf(discordbotsUpdateURL, user.ID)
logrus.Info("running discordbots.org update thread in background...")
discordbotsUpdater := &discordbotsUpdater{
discordSession: session,
}
go discordbotsUpdater.runDiscordbotsUpdater(session, discordbotsUpdateExitChan)
}
logrus.Debug("initializing DNS resolve handler...")
resolveHandler := &discord1111resolver.ResolveHandler{
DNSClient: &dns.Client{
Net: "tcp-tls", // enable DNS over TLS
},
DiscordBotUser: user,
}
resolveHandler.Initialize()
session.AddHandler(resolveHandler.Handle)
// Wait here until CTRL-C or other term signal is received.
logrus.Info("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
if discordbotsUpdateExitChan != nil {
logrus.Debug("stopping discordbots.org update task...")
discordbotsUpdateExitChan <- struct{}{}
}
logrus.Debug("closing Discord session...")
if err := session.Close(); err != nil {
logrus.WithError(err).Warn("could not close discord session")
}
logrus.Info("bye")
os.Exit(0)
}

type discordbotsUpdater struct {
http.Client
discordSession *discordgo.Session
}

func (discordbotsUpdater *discordbotsUpdater) runDiscordbotsUpdater(session *discordgo.Session, exitChannel chan interface{}) {
for {
select {
case <-exitChannel:
return
case <-time.After(discordbotsUpdateInterval):
logrus.Debug("updating discordbots.org statistics...")
discordbotsUpdater.updateDiscordbotsAPI(session)
break
}
}
}

func (discordbotsUpdater *discordbotsUpdater) updateDiscordbotsAPI(session *discordgo.Session) {
var guildCount int
var afterID string
for {
// request user guilds
userGuilds, err := session.UserGuilds(100, "", afterID)
if err != nil {
logrus.WithError(err).Warn("could not request guild list")
}
// increase total guild count
guildCount += len(userGuilds)
if len(userGuilds) < 100 {
break
}
// set new afterID to request the new list
afterID = userGuilds[99].ID
}
updateData := struct {
ServerCount int `json:"server_count"`
}{
ServerCount: guildCount,
}
marshalBytes, err := json.Marshal(updateData)
if err != nil {
logrus.WithError(err).Warn("could not marshal discordbots.org update data")
return
}
request, err := http.NewRequest(http.MethodPost, discordbotsUpdateURL, bytes.NewReader(marshalBytes))
if err != nil {
logrus.WithError(err).Warn("could not create http request for the discordbots.org API")
return
}
// set authorization and content type
request.Header["Authorization"] = []string{discordbotsToken}
request.Header["Content-Type"] = []string{"application/json"}
resp, err := discordbotsUpdater.Do(request)
if err != nil {
logrus.WithError(err).Warn("an error occurred while updating the discordbots.org data")
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logrus.WithField("http-status-code", resp.StatusCode).Warn("received an unexpected http status code")
}
logrus.Debug("successfully updated discordbots.org statistics.")
}
2 changes: 2 additions & 0 deletions doc.go
@@ -0,0 +1,2 @@
// Package discord1111resolverroot contains the Discord 1111Resolver bot.
package discord1111resolverroot

0 comments on commit fc7411d

Please sign in to comment.