Skip to content

Commit

Permalink
Debugged updates et al
Browse files Browse the repository at this point in the history
  • Loading branch information
bsoule committed Nov 9, 2023
1 parent 506bfad commit 8afc2d8
Show file tree
Hide file tree
Showing 5 changed files with 171 additions and 115 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
*.log
node_modules/
.scratch
.vscode/
238 changes: 139 additions & 99 deletions lib/beebot.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// --------------------------------- 80chars ---------------------------------->
var botils = require('./botils.js')
const botils = require('./botils.js')

if (process.env.REDIS_URL) {
//var rtg = require("url").parse(process.env.REDIS_URL)
Expand All @@ -21,7 +21,7 @@ var bots = []

// handle a message and pass it through to the Beeminder server
var handleMessage = function(rtm, message) {
//console.log("DEBUG4: handleMessage", message)
console.log("handleMessage", message)
// I hope this is safe: the bot was responding to its own
// messages when i use chat.message.. which is no good,
// so skip if it has a subtype of "bot_message"? again, no
Expand Down Expand Up @@ -63,61 +63,95 @@ var stopBot = function(teamId) {
var startBot = function(teamId, rurl=null) {
var rediskey = `beebot.teamid.${teamId}`
redis.hgetall(rediskey, function(err, obj) {
//console.log("DEBUG: obj and err are both null!")
//console.log(`DEBUG: teamId/obj/err = ${teamId} / ${obj} / ${err}`)
console.log("DEBUG: teamId/obj/err", teamId, obj, err)
const RtmClient = require('@slack/client').RtmClient
const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS
const MemoryDataStore = require('@slack/client').MemoryDataStore
if (obj === null && rurl !== null) {
botils.blurt(rurl, "Sad panda. Can't create a bot to listen here. " +
`redis.hgetall("beebot.teamid.${teamId}") returned null ` +
"so we can't look up the bot access token for the Slack RTM client.")
return
}
const rtm = new RtmClient(obj.bot_access_token, {
useRtmConnect: true,
dataStore: new MemoryDataStore(),
autoReconnect: true,
})
// RtmClient constructor appears to be broken, not storing the token that
// is passed in the constructor, but expecting it to be around
rtm.token = obj.bot_access_token

rtm.on('message', function(message) {
if (!message.text) { return }
var regexpString = "<@" + rtm.activeUserId + ">"
if (message.text.match(new RegExp(regexpString))) {
handleMessage(rtm, message)
}
if (message.channel.match(/^D/) && message.team && !message.command) {
handleMessage(rtm, message)
}
if (message.text.match(new RegExp(/\+\+|--/))) {
console.log('spotted a ++')
karmabot.handleMessage(rtm, message)
try {
//console.log("DEBUG: obj and err are both null!")
//console.log("DEBUG: teamId/obj/err", teamId, obj, err)
const RtmClient = require('@slack/client').RtmClient
const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS
const MemoryDataStore = require('@slack/client').MemoryDataStore

if (obj === null && rurl !== null) {
botils.blurt(rurl, "Sad panda. Can't create a bot to listen here. " +
`redis.hgetall("beebot.teamid.${teamId}") returned null ` +
"so we can't look up the bot access token for the Slack RTM client.")
return
}
})
const logLevel = 'info'
const rtm = new RtmClient(obj.bot_access_token, {
useRtmConnect: true,
dataStore: new MemoryDataStore(),
autoReconnect: true,
logLevel: logLevel,
logger: (level, msg) => {
if (logLevel == level) {
console.log("RTM LOG", level, msg)
}
return
},
})

rtm.on('error', (error) => {
console.log(error)
console.log(typeof(error))
console.log("mysterycrashererror")
})
rtm.on('message', function(message) {
if (!message.text) { return }
var regexpString = "<@" + rtm.activeUserId + ">"
if (message.text.match(new RegExp(regexpString))) {
handleMessage(rtm, message)
}
if (message.channel.match(/^D/) && message.team && !message.command) {
handleMessage(rtm, message)
}
if (message.text.match(new RegExp(/\+\+|--/))) {
console.log('spotted a ++')
karmabot.handleMessage(rtm, message)
}
})

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function(rtmStartData) {
//console.log("AUTHENTICATED!", Object.keys(rtmStartData))
rtm.userId = rtmStartData.self.id
})
rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
//console.log("CONNEXTION READY?")
console.log("RTM is CONNECTED?", rtm.connected)
})
rtm.on('error', (error) => {
//console.log("mysterycrashererror")
console.error("ERROR", error.msg)
})

rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function(rtmStartData) {
//console.log("AUTHENTICATED!", rtmStartData.self.name, rtmStartData.team.name)
rtm.userId = rtmStartData.self.id
})
rtm.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
//console.log("CONNEXTION READY?")
//console.log("RTM is CONNECTED?", rtm.connected)
})
rtm.on(CLIENT_EVENTS.RTM.DISCONNECT, () => {
//console.log("RTM is DISCONNECTED?", !rtm.connected)
})
rtm.on(CLIENT_EVENTS.RTM.UNABLE_TO_RTM_START, (error) => {
// could not start the connection with slack
if (error.message === "account_inactive" ||
error.message === "invalid_auth") {
// delete the bot
redis.del(rediskey, function(err, obj) {
console.log("redis delete callback", err, obj)
})
}
console.error("UNABLE_TO_RTM_START", error.message)
})
rtm.on(CLIENT_EVENTS.RTM.WS_ERROR, (error) => {
console.error("WS_ERROR", error)
})
rtm.on(CLIENT_EVENTS.WEB.RATE_LIMITED, (error) => {
console.error("WEB RATE LIMITED", error)
})
rtm.on('Ratelimited', (error) => {
console.error("RATE LIMITED", error)
})

stopBot(teamId)
rtm.start()
rtm.teamId = teamId
bots.push(rtm)
} catch (error) {
console.error("caught error creating rtm client", error)
console.error(error.message)
return
}

stopBot(teamId)
rtm.start()
rtm.teamId = teamId
bots.push(rtm)
})
}

Expand All @@ -134,71 +168,77 @@ var handleCreateBot = function(req, resp) {
}

var handleZeno = (req, res) => {
console.log("handleZeno")
//var rtm = bots.filter((b) => { return b.teamId === req.body.team_id })[0]
var rtm = rtmForTeam(req.body.team_id)
if (rtm === undefined || rtm === null) {
console.log("no rtm for team " + req.body.team_id)
res.send("500"); return
console.error("no rtm for team " + req.body.team_id)
res.status(500).send('no rtm for team team_id'); return
}
if (rtm.connected === false) {
console.error("rtm not connected")
rtm.start()
}
console.log(`rtm found: attempts:${rtm._connAttempts}, connected:${rtm.connected}, token:${rtm._token}`)
var WebClient = require('@slack/client').WebClient
var webClient = new WebClient(rtm._token)
console.log(`webClient created: token:${webClient.token}`)

if (req.body.channel) {
console.log(`req.body.channel = ${req.body.channel}`)
webClient.conversations.list({}, (error, response) => {
if (!response.ok) {
res.send("error!")
console.log("error in conversations.list: " + response.error)
return
} //TODO: alert
console.log(`got ${response.channels.length} channels`)
for (var i = 0; i < response.channels.length; i++) {
var channel = response.channels[i]
if (channel.name !== req.body.channel.replace('#', '')) { continue }
console.log(`found channel ${channel.name} (${channel.id})`)
webClient.chat.postMessage(channel.id, req.body.message)
console.log(`sent message`)
//rtm.sendMessage(req.body.message, channel.id)
res.send("ok")
return
}
console.log(`could not find channel ${req.body.channel}`)
res.send("could not find a channel with the name " + req.body.channel)
})
try {
webClient.conversations.list({}, (error, response) => {
if (!response.ok) {
console.error("error in conversations.list: " + response)
console.error("error: ", error)
console.error("response.headers", response.headers())
res.send("error!"); return
} //TODO: alert
for (var i = 0; i < response.channels.length; i++) {
var channel = response.channels[i]
if (channel.name !== req.body.channel.replace('#', '')) { continue }
webClient.chat.postMessage(channel.id, req.body.message)
res.send("ok"); return
}
res.status(404).send("could not find a channel with the name " + req.body.channel)
})
} catch (error) {
console.error("error in conversations.list: " + error.message)
res.status(500).send("error in handleZeno: " + error.message)
return
}
return
}

// else default to a DM
// TODO: when would we have a user here? I don't understand this
var user = rtm.dataStore.getUserById(req.body.user_id)
console.log("datastore user", user)
if (user) {
console.log("looking up user DM in datatstore")
var dm = rtm.dataStore.getDMByName(user.name)
console.log("looked up user DM in datatstore")
if (dm) {
console.log("found user DM in datatstore")
rtm.sendMessage(req.body.message, dm.id)
console.log("sent message")
res.send("ok")
return
try {
if (user) {
var dm = rtm.dataStore.getDMByName(user.name)
if (dm) {
rtm.sendMessage(req.body.message, dm.id)
res.send("ok")
return
}
}
} catch (error) {
console.error("error in datastore user: " + error.message)
res.status(500).send("error in handleZeno: " + error.message)
return
}

// open the dm channel if we didn't find a user
//webClient.conversations.open(_token, (error, response) => {
console.log("opening webClient conversations: ")
webClient.conversations.open({token: rtm._token, users: req.body.user_id},
(error, response) => {
console.log("webClient conversations.open callback: ", error, response)
webClient.chat.postMessage(response.channel.id, req.body.message)
console.log("posted message")
//rtm.sendMessage(req.body.message, response.channel.id)
try {
webClient.conversations.open({token: rtm._token, users: req.body.user_id},
(error, response) => {
//console.log("webClient conversations.open callback: ", error, response)
webClient.chat.postMessage(response.channel.id, req.body.message)
//rtm.sendMessage(req.body.message, response.channel.id)
res.send("ok"); return
}
)
} catch (error) {
console.error("error in webClient conversations.open: " + error.message)
res.status(500).send("error in handleZeno: " + error.message)
return
})
}

res.send("ok")
return
Expand Down
2 changes: 1 addition & 1 deletion lib/tock.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ var updateBeeminder = (teamId, userId, slug, tock) => {

// end all tocks with end dates < now, post as failures to channel
var checkTocks = () => {
console.log("ttock checkTocks")
//console.log("ttock checkTocks")
redis.keys(rkey("tocks", "*"), (err, obj) => {
for (var i = 0; i < obj.length; i++) {
var chan = obj[i].split(".").pop()
Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
{
"name": "beebot",
"version": "1.0.1",
"version": "1.0.2",
"description": "A helpful bot for interacting with Beeminder",
"main": "server.js",
"engines": {
"node": "8"
"node": "20.x"
},
"dependencies": {
"@slack/client": "^3.15.0",
"@slack/client": "^3.16.1-sec.2",
"body-parser": "^1.18.2",
"dotenv": "^4.0.0",
"express": "^4.16.2",
"http": "0.0.0",
"https": "^1.0.0",
"nodemon": "^2.0.22",
"redis": "^3.0.0",
"request": "^2.83.0"
},
"devDependencies": {},
"babel": {},
"scripts": {
"start": "node server.js"
"start": "nodemon server.js"
},
"author": "Beeminder",
"license": "MIT",
Expand Down
Loading

0 comments on commit 8afc2d8

Please sign in to comment.