Skip to content

Instantly share code, notes, and snippets.

@JeanRibes
Created March 11, 2021 15:48
Show Gist options
  • Save JeanRibes/a4d5f0ae7cf2c2449b200a31ddf99e33 to your computer and use it in GitHub Desktop.
Save JeanRibes/a4d5f0ae7cf2c2449b200a31ddf99e33 to your computer and use it in GitHub Desktop.
Minecraft Chat <-> ComputerCraft <-> Discord Bot <-> Discord
package main
import (
"bufio"
"fmt"
"github.com/bwmarrin/discordgo"
"golang.org/x/net/websocket"
"net/http"
"os"
"os/signal"
"syscall"
)
var chatWebsocket func(s string)
var sess *discordgo.Session
//var computercraftCommand discordgo.ApplicationCommand
var chatCommand discordgo.ApplicationCommand = discordgo.ApplicationCommand{
Name: "mc",
Description: "Envoie un message dans le chat Minecraft",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "message",
Description: "Message à envoyer",
Required: true,
},
},
}
var chatChannelId = "814779001540182016"
var guildId = "740937779374194750"
/*
Protocole: on reçoit le channelId du Computer
on répond avec OK ou FAIL
on forward les messages suivants dans Discord; et inversement
*/
func httpServ() {
http.Handle("/chat", websocket.Handler(WSChatServer))
err := http.ListenAndServe(":4042", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
func main() {
var err error
sess, err = discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))
if err != nil {
fmt.Println("error creating Discord session,", err)
return
}
sess.AddHandler(messageCreate)
sess.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsDirectMessages | discordgo.IntentsGuildMessages | discordgo.IntentsDirectMessageReactions | discordgo.IntentsGuildMessageReactions)
err = sess.Open()
if err != nil {
fmt.Println("error opening connection,", err)
return
} else {
fmt.Println("OCbridgeBot tourne !")
}
go httpServ()
sess.AddHandler(slashCommandHandler)
cccmd, acce := sess.ApplicationCommandCreate(sess.State.User.ID, guildId, &chatCommand)
he(acce)
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
<-sc
he(sess.ApplicationCommandDelete(sess.State.User.ID, "740937779374194750", cccmd.ID))
he(sess.Close())
}
func he(err error) {
if err != nil {
panic(err)
}
}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
if m.Author.ID == s.State.User.ID {
return
}
if m.Content[0] != '!' && m.Content[0] != '/' && m.Content[0] != '.' && m.Content[0] != '>' && m.Content[0] != '\\' && m.Content[0] != '-' && m.Content[0] != ':' {
if m.ChannelID == chatChannelId {
println("got chat message, forwarding")
if chatWebsocket != nil {
chatWebsocket(fmt.Sprintf("Discord: <%s> %s", m.Author.Username, m.Content))
}
}
}
}
func WSChatServer(ws *websocket.Conn) { // un par WS
r := bufio.NewReadWriter(
bufio.NewReader(ws),
bufio.NewWriter(ws))
fmt.Printf("new client: %s\n", ws.RemoteAddr())
sender := func(s string) {
_, werr := r.WriteString(s)
ghe(werr)
ghe(r.Flush())
}
chatWebsocket = sender
for {
s, re := r.ReadString('\n')
he(re)
_, se := sess.ChannelMessageSend(chatChannelId, "MC: "+s)
he(se)
}
}
func slashCommandHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
if i.Data.Name == "mc" {
opt := i.Data.Options[0]
fmt.Printf("mc: name=%s value=%v\n", opt.Name, opt.Value)
/*he(s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseAcknowledge,
}))*/
he(s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionApplicationCommandResponseData{
TTS: false,
Content: fmt.Sprintf("vous avez envoyé '%s'", opt.Value),
Embeds: nil,
AllowedMentions: nil,
},
}))
he(s.InteractionResponseDelete(sess.State.User.ID, i.Interaction)) //vire la réponse du bot dans le chat, en
// laissant l'historique de l'utilisateur
}
}
func ghe(err error) {
if err != nil {
println(err.Error())
}
}
module mcbridge
go 1.16
require (
github.com/bwmarrin/discordgo v0.23.3-0.20210301043234-abe5ba6f0f66
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110
)
var s= new WebSocket("ws://localhost:4042/chat")
s.onmessage = console.log
s.send("<greg414> salut\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment