commands.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "math"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "github.com/skip2/go-qrcode"
  26. "maunium.net/go/maulogger/v2"
  27. "go.mau.fi/whatsmeow"
  28. "go.mau.fi/whatsmeow/appstate"
  29. "go.mau.fi/whatsmeow/types"
  30. "maunium.net/go/mautrix"
  31. "maunium.net/go/mautrix/appservice"
  32. "maunium.net/go/mautrix/event"
  33. "maunium.net/go/mautrix/format"
  34. "maunium.net/go/mautrix/id"
  35. )
  36. type CommandHandler struct {
  37. bridge *Bridge
  38. log maulogger.Logger
  39. }
  40. // NewCommandHandler creates a CommandHandler
  41. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  42. return &CommandHandler{
  43. bridge: bridge,
  44. log: bridge.Log.Sub("Command handler"),
  45. }
  46. }
  47. // CommandEvent stores all data which might be used to handle commands
  48. type CommandEvent struct {
  49. Bot *appservice.IntentAPI
  50. Bridge *Bridge
  51. Portal *Portal
  52. Handler *CommandHandler
  53. RoomID id.RoomID
  54. User *User
  55. Command string
  56. Args []string
  57. ReplyTo id.EventID
  58. }
  59. // Reply sends a reply to command as notice
  60. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  61. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  62. content.MsgType = event.MsgNotice
  63. intent := ce.Bot
  64. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  65. intent = ce.Portal.MainIntent()
  66. }
  67. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  68. if err != nil {
  69. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  70. }
  71. }
  72. // Handle handles messages to the bridge
  73. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string, replyTo id.EventID) {
  74. args := strings.Fields(message)
  75. if len(args) == 0 {
  76. args = []string{"unknown-command"}
  77. }
  78. ce := &CommandEvent{
  79. Bot: handler.bridge.Bot,
  80. Bridge: handler.bridge,
  81. Portal: handler.bridge.GetPortalByMXID(roomID),
  82. Handler: handler,
  83. RoomID: roomID,
  84. User: user,
  85. Command: strings.ToLower(args[0]),
  86. Args: args[1:],
  87. ReplyTo: replyTo,
  88. }
  89. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  90. handler.CommandMux(ce)
  91. }
  92. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  93. switch ce.Command {
  94. case "login":
  95. handler.CommandLogin(ce)
  96. case "ping-matrix":
  97. handler.CommandPingMatrix(ce)
  98. case "logout-matrix":
  99. handler.CommandLogoutMatrix(ce)
  100. case "help":
  101. handler.CommandHelp(ce)
  102. case "version":
  103. handler.CommandVersion(ce)
  104. case "reconnect", "connect":
  105. handler.CommandReconnect(ce)
  106. case "disconnect":
  107. handler.CommandDisconnect(ce)
  108. case "ping":
  109. handler.CommandPing(ce)
  110. case "delete-session":
  111. handler.CommandDeleteSession(ce)
  112. case "delete-portal":
  113. handler.CommandDeletePortal(ce)
  114. case "delete-all-portals":
  115. handler.CommandDeleteAllPortals(ce)
  116. case "discard-megolm-session", "discard-session":
  117. handler.CommandDiscardMegolmSession(ce)
  118. case "dev-test":
  119. handler.CommandDevTest(ce)
  120. case "set-pl":
  121. handler.CommandSetPowerLevel(ce)
  122. case "logout":
  123. handler.CommandLogout(ce)
  124. case "toggle":
  125. handler.CommandToggle(ce)
  126. case "set-relay", "unset-relay", "login-matrix", "sync", "list", "search", "open", "pm", "invite-link", "check-invite", "join", "create", "accept":
  127. if !ce.User.HasSession() {
  128. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  129. return
  130. } else if !ce.User.IsLoggedIn() {
  131. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  132. return
  133. }
  134. switch ce.Command {
  135. case "set-relay":
  136. handler.CommandSetRelay(ce)
  137. case "unset-relay":
  138. handler.CommandUnsetRelay(ce)
  139. case "login-matrix":
  140. handler.CommandLoginMatrix(ce)
  141. case "sync":
  142. handler.CommandSync(ce)
  143. case "list":
  144. handler.CommandList(ce)
  145. case "search":
  146. handler.CommandSearch(ce)
  147. case "open":
  148. handler.CommandOpen(ce)
  149. case "pm":
  150. handler.CommandPM(ce)
  151. case "invite-link":
  152. handler.CommandInviteLink(ce)
  153. case "check-invite":
  154. handler.CommandCheckInvite(ce)
  155. case "join":
  156. handler.CommandJoin(ce)
  157. case "create":
  158. handler.CommandCreate(ce)
  159. case "accept":
  160. handler.CommandAccept(ce)
  161. }
  162. default:
  163. ce.Reply("Unknown command, use the `help` command for help.")
  164. }
  165. }
  166. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  167. if handler.bridge.Crypto == nil {
  168. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  169. } else if !ce.User.Admin {
  170. ce.Reply("Only the bridge admin can reset Megolm sessions")
  171. } else {
  172. handler.bridge.Crypto.ResetSession(ce.RoomID)
  173. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  174. }
  175. }
  176. const cmdSetRelayHelp = `set-relay - Relay messages in this room through your WhatsApp account.`
  177. func (handler *CommandHandler) CommandSetRelay(ce *CommandEvent) {
  178. if !handler.bridge.Config.Bridge.Relay.Enabled {
  179. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  180. } else if ce.Portal == nil {
  181. ce.Reply("This is not a portal room")
  182. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  183. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  184. } else {
  185. ce.Portal.RelayUserID = ce.User.MXID
  186. ce.Portal.Update()
  187. ce.Reply("Messages from non-logged-in users in this room will now be bridged through your WhatsApp account")
  188. }
  189. }
  190. const cmdUnsetRelayHelp = `unset-relay - Stop relaying messages in this room.`
  191. func (handler *CommandHandler) CommandUnsetRelay(ce *CommandEvent) {
  192. if !handler.bridge.Config.Bridge.Relay.Enabled {
  193. ce.Reply("Relay mode is not enabled on this instance of the bridge")
  194. } else if ce.Portal == nil {
  195. ce.Reply("This is not a portal room")
  196. } else if handler.bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
  197. ce.Reply("Only admins are allowed to enable relay mode on this instance of the bridge")
  198. } else {
  199. ce.Portal.RelayUserID = ""
  200. ce.Portal.Update()
  201. ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
  202. }
  203. }
  204. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  205. }
  206. const cmdVersionHelp = `version - View the bridge version`
  207. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  208. linkifiedVersion := fmt.Sprintf("v%s", Version)
  209. if Tag == Version {
  210. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  211. } else if len(Commit) > 8 {
  212. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  213. }
  214. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  215. }
  216. const cmdInviteLinkHelp = `invite-link [--reset] - Get an invite link to the current group chat, optionally regenerating the link and revoking the old link.`
  217. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  218. reset := len(ce.Args) > 0 && strings.ToLower(ce.Args[0]) == "--reset"
  219. if ce.Portal == nil {
  220. ce.Reply("Not a portal room")
  221. } else if ce.Portal.IsPrivateChat() {
  222. ce.Reply("Can't get invite link to private chat")
  223. } else if ce.Portal.IsBroadcastList() {
  224. ce.Reply("Can't get invite link to broadcast list")
  225. } else if link, err := ce.User.Client.GetGroupInviteLink(ce.Portal.Key.JID, reset); err != nil {
  226. ce.Reply("Failed to get invite link: %v", err)
  227. } else {
  228. ce.Reply(link)
  229. }
  230. }
  231. const cmdCheckInviteHelp = `check-invite <invite link> - Resolve an invite link and check which group it points at.`
  232. const inviteLinkPrefix = "https://chat.whatsapp.com/"
  233. func (handler *CommandHandler) CommandCheckInvite(ce *CommandEvent) {
  234. if len(ce.Args) == 0 {
  235. ce.Reply("**Usage:** `join <invite link>`")
  236. return
  237. } else if len(ce.Args[0]) <= len(inviteLinkPrefix) || ce.Args[0][:len(inviteLinkPrefix)] != inviteLinkPrefix {
  238. ce.Reply("That doesn't look like a WhatsApp invite link")
  239. return
  240. }
  241. group, err := ce.User.Client.GetGroupInfoFromLink(ce.Args[0])
  242. if err != nil {
  243. ce.Reply("Failed to get group info: %v", err)
  244. return
  245. }
  246. ce.Reply("That invite link points at %s (`%s`)", group.Name, group.JID)
  247. }
  248. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  249. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  250. if len(ce.Args) == 0 {
  251. ce.Reply("**Usage:** `join <invite link>`")
  252. return
  253. } else if len(ce.Args[0]) <= len(inviteLinkPrefix) || ce.Args[0][:len(inviteLinkPrefix)] != inviteLinkPrefix {
  254. ce.Reply("That doesn't look like a WhatsApp invite link")
  255. return
  256. }
  257. jid, err := ce.User.Client.JoinGroupWithLink(ce.Args[0])
  258. if err != nil {
  259. ce.Reply("Failed to join group: %v", err)
  260. return
  261. }
  262. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  263. ce.Reply("Successfully joined group `%s`, the portal should be created momentarily", jid)
  264. }
  265. func (handler *CommandHandler) CommandAccept(ce *CommandEvent) {
  266. if ce.Portal == nil || len(ce.ReplyTo) == 0 {
  267. ce.Reply("You must reply to a group invite message when using this command.")
  268. } else if evt, err := ce.Portal.MainIntent().GetEvent(ce.RoomID, ce.ReplyTo); err != nil {
  269. handler.log.Errorln("Failed to get event %s to handle !wa accept command: %v", ce.ReplyTo, err)
  270. ce.Reply("Failed to get reply event")
  271. } else if meta, ok := evt.Content.Raw[inviteMetaField].(map[string]interface{}); !ok {
  272. ce.Reply("That doesn't look like a group invite message.")
  273. } else if jid, inviter, code, expiration, ok := parseInviteMeta(meta); !ok {
  274. ce.Reply("That doesn't look like a group invite message.")
  275. } else if inviter.User == ce.User.JID.User {
  276. ce.Reply("You can't accept your own invites")
  277. } else if err = ce.User.Client.JoinGroupWithInvite(jid, inviter, code, expiration); err != nil {
  278. ce.Reply("Failed to accept group invite: %v", err)
  279. } else {
  280. ce.Reply("Successfully accepted the invite, the portal should be created momentarily")
  281. }
  282. }
  283. const cmdCreateHelp = `create - Create a group chat.`
  284. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  285. if ce.Portal != nil {
  286. ce.Reply("This is already a portal room")
  287. return
  288. }
  289. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  290. if err != nil {
  291. ce.Reply("Failed to get room members: %v", err)
  292. return
  293. }
  294. var roomNameEvent event.RoomNameEventContent
  295. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  296. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  297. handler.log.Errorln("Failed to get room name to create group:", err)
  298. ce.Reply("Failed to get room name")
  299. return
  300. } else if len(roomNameEvent.Name) == 0 {
  301. ce.Reply("Please set a name for the room first")
  302. return
  303. }
  304. var encryptionEvent event.EncryptionEventContent
  305. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  306. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  307. ce.Reply("Failed to get room encryption status")
  308. return
  309. }
  310. var participants []types.JID
  311. participantDedup := make(map[types.JID]bool)
  312. participantDedup[ce.User.JID.ToNonAD()] = true
  313. participantDedup[types.EmptyJID] = true
  314. for userID := range members.Joined {
  315. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  316. if !ok {
  317. user := handler.bridge.GetUserByMXID(userID)
  318. if user != nil && !user.JID.IsEmpty() {
  319. jid = user.JID.ToNonAD()
  320. }
  321. }
  322. if !participantDedup[jid] {
  323. participantDedup[jid] = true
  324. participants = append(participants, jid)
  325. }
  326. }
  327. handler.log.Infofln("Creating group for %s with name %s and participants %+v", ce.RoomID, roomNameEvent.Name, participants)
  328. resp, err := ce.User.Client.CreateGroup(roomNameEvent.Name, participants)
  329. if err != nil {
  330. ce.Reply("Failed to create group: %v", err)
  331. return
  332. }
  333. portal := ce.User.GetPortalByJID(resp.JID)
  334. portal.roomCreateLock.Lock()
  335. defer portal.roomCreateLock.Unlock()
  336. if len(portal.MXID) != 0 {
  337. portal.log.Warnln("Detected race condition in room creation")
  338. // TODO race condition, clean up the old room
  339. }
  340. portal.MXID = ce.RoomID
  341. portal.Name = roomNameEvent.Name
  342. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  343. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  344. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  345. if err != nil {
  346. portal.log.Warnln("Failed to enable encryption in room:", err)
  347. if errors.Is(err, mautrix.MForbidden) {
  348. ce.Reply("I don't seem to have permission to enable encryption in this room.")
  349. } else {
  350. ce.Reply("Failed to enable encryption in room: %v", err)
  351. }
  352. }
  353. portal.Encrypted = true
  354. }
  355. portal.Update()
  356. portal.UpdateBridgeInfo()
  357. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  358. }
  359. func parseInviteMeta(meta map[string]interface{}) (jid, inviter types.JID, code string, expiration int64, ok bool) {
  360. var fieldFound bool
  361. code, fieldFound = meta["code"].(string)
  362. if !fieldFound {
  363. return
  364. }
  365. expirationStr, fieldFound := meta["expiration"].(string)
  366. if !fieldFound {
  367. return
  368. }
  369. inviterStr, fieldFound := meta["inviter"].(string)
  370. if !fieldFound {
  371. return
  372. }
  373. jidStr, fieldFound := meta["jid"].(string)
  374. if !fieldFound {
  375. return
  376. }
  377. var err error
  378. expiration, err = strconv.ParseInt(expirationStr, 10, 64)
  379. if err != nil {
  380. return
  381. }
  382. inviter, err = types.ParseJID(inviterStr)
  383. if err != nil {
  384. return
  385. }
  386. jid, err = types.ParseJID(jidStr)
  387. if err != nil {
  388. return
  389. }
  390. ok = true
  391. return
  392. }
  393. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  394. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  395. if ce.Portal == nil {
  396. ce.Reply("Not a portal room")
  397. return
  398. }
  399. var level int
  400. var userID id.UserID
  401. var err error
  402. if len(ce.Args) == 1 {
  403. level, err = strconv.Atoi(ce.Args[0])
  404. if err != nil {
  405. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  406. return
  407. }
  408. userID = ce.User.MXID
  409. } else if len(ce.Args) == 2 {
  410. userID = id.UserID(ce.Args[0])
  411. _, _, err := userID.Parse()
  412. if err != nil {
  413. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  414. return
  415. }
  416. level, err = strconv.Atoi(ce.Args[1])
  417. if err != nil {
  418. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  419. return
  420. }
  421. } else {
  422. ce.Reply("**Usage:** `set-pl [user] <level>`")
  423. return
  424. }
  425. intent := ce.Portal.MainIntent()
  426. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  427. if err != nil {
  428. ce.Reply("Failed to set power levels: %v", err)
  429. }
  430. }
  431. const cmdLoginHelp = `login - Link the bridge to your WhatsApp account as a web client`
  432. // CommandLogin handles login command
  433. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  434. if ce.User.Session != nil {
  435. if ce.User.IsConnected() {
  436. ce.Reply("You're already logged in")
  437. } else {
  438. ce.Reply("You're already logged in. Perhaps you wanted to `reconnect`?")
  439. }
  440. return
  441. }
  442. qrChan, err := ce.User.Login(context.Background())
  443. if err != nil {
  444. ce.User.log.Errorf("Failed to log in:", err)
  445. ce.Reply("Failed to log in: %v", err)
  446. return
  447. }
  448. var qrEventID id.EventID
  449. for item := range qrChan {
  450. switch item {
  451. case whatsmeow.QRChannelSuccess:
  452. jid := ce.User.Client.Store.ID
  453. ce.Reply("Successfully logged in as +%s (device #%d)", jid.User, jid.Device)
  454. case whatsmeow.QRChannelTimeout:
  455. ce.Reply("QR code timed out. Please restart the login.")
  456. case whatsmeow.QRChannelErrUnexpectedEvent:
  457. ce.Reply("Failed to log in: unexpected connection event from server")
  458. case whatsmeow.QRChannelScannedWithoutMultidevice:
  459. ce.Reply("Please enable the WhatsApp multidevice beta and scan the QR code again.")
  460. default:
  461. qrEventID = ce.User.sendQR(ce, item.Code, qrEventID)
  462. }
  463. }
  464. _, _ = ce.Bot.RedactEvent(ce.RoomID, qrEventID)
  465. }
  466. func (user *User) sendQR(ce *CommandEvent, code string, prevEvent id.EventID) id.EventID {
  467. url, ok := user.uploadQR(ce, code)
  468. if !ok {
  469. return prevEvent
  470. }
  471. content := event.MessageEventContent{
  472. MsgType: event.MsgImage,
  473. Body: code,
  474. URL: url.CUString(),
  475. }
  476. if len(prevEvent) != 0 {
  477. content.SetEdit(prevEvent)
  478. }
  479. resp, err := ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &content)
  480. if err != nil {
  481. user.log.Errorln("Failed to send edited QR code to user:", err)
  482. } else if len(prevEvent) == 0 {
  483. prevEvent = resp.EventID
  484. }
  485. return prevEvent
  486. }
  487. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  488. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  489. if err != nil {
  490. user.log.Errorln("Failed to encode QR code:", err)
  491. ce.Reply("Failed to encode QR code: %v", err)
  492. return id.ContentURI{}, false
  493. }
  494. bot := user.bridge.AS.BotClient()
  495. resp, err := bot.UploadBytes(qrCode, "image/png")
  496. if err != nil {
  497. user.log.Errorln("Failed to upload QR code:", err)
  498. ce.Reply("Failed to upload QR code: %v", err)
  499. return id.ContentURI{}, false
  500. }
  501. return resp.ContentURI, true
  502. }
  503. const cmdLogoutHelp = `logout - Unlink the bridge from your WhatsApp account`
  504. // CommandLogout handles !logout command
  505. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  506. if ce.User.Session == nil {
  507. ce.Reply("You're not logged in.")
  508. return
  509. } else if !ce.User.IsLoggedIn() {
  510. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  511. return
  512. }
  513. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  514. if puppet.CustomMXID != "" {
  515. err := puppet.SwitchCustomMXID("", "")
  516. if err != nil {
  517. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  518. }
  519. }
  520. err := ce.User.Client.Logout()
  521. if err != nil {
  522. ce.User.log.Warnln("Error while logging out:", err)
  523. ce.Reply("Unknown error while logging out: %v", err)
  524. return
  525. }
  526. ce.User.Session = nil
  527. ce.User.removeFromJIDMap(StateLoggedOut)
  528. ce.User.DeleteConnection()
  529. ce.User.DeleteSession()
  530. ce.Reply("Logged out successfully.")
  531. }
  532. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  533. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  534. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  535. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  536. return
  537. }
  538. if ce.User.Session == nil {
  539. ce.Reply("You're not logged in.")
  540. return
  541. }
  542. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  543. if customPuppet == nil {
  544. ce.Reply("You're not logged in with your Matrix account.")
  545. return
  546. }
  547. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  548. customPuppet.EnablePresence = !customPuppet.EnablePresence
  549. var newPresence types.Presence
  550. if customPuppet.EnablePresence {
  551. newPresence = types.PresenceAvailable
  552. ce.Reply("Enabled presence bridging")
  553. } else {
  554. newPresence = types.PresenceUnavailable
  555. ce.Reply("Disabled presence bridging")
  556. }
  557. if ce.User.IsLoggedIn() {
  558. err := ce.User.Client.SendPresence(newPresence)
  559. if err != nil {
  560. ce.User.log.Warnln("Failed to set presence:", err)
  561. }
  562. }
  563. }
  564. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  565. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  566. if customPuppet.EnableReceipts {
  567. ce.Reply("Enabled read receipt bridging")
  568. } else {
  569. ce.Reply("Disabled read receipt bridging")
  570. }
  571. }
  572. customPuppet.Update()
  573. }
  574. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  575. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  576. if ce.User.Session == nil && ce.User.Client == nil {
  577. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  578. return
  579. }
  580. ce.User.removeFromJIDMap(StateLoggedOut)
  581. ce.User.DeleteConnection()
  582. ce.User.DeleteSession()
  583. ce.Reply("Session information purged")
  584. }
  585. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  586. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  587. if ce.User.Client == nil {
  588. if ce.User.Session == nil {
  589. ce.Reply("You're not logged into WhatsApp. Please log in first.")
  590. } else {
  591. ce.User.Connect()
  592. ce.Reply("Started connecting to WhatsApp")
  593. }
  594. } else {
  595. ce.User.DeleteConnection()
  596. ce.User.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  597. ce.User.Connect()
  598. ce.Reply("Restarted connection to WhatsApp")
  599. }
  600. }
  601. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  602. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  603. if ce.User.Client == nil {
  604. ce.Reply("You don't have a WhatsApp connection.")
  605. return
  606. }
  607. ce.User.DeleteConnection()
  608. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  609. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  610. }
  611. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  612. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  613. if ce.User.Session == nil {
  614. if ce.User.Client != nil {
  615. ce.Reply("Connected to WhatsApp, but not logged in.")
  616. } else {
  617. ce.Reply("You're not logged into WhatsApp.")
  618. }
  619. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  620. ce.Reply("You're logged in as +%s (device #%d), but you don't have a WhatsApp connection.", ce.User.JID.User, ce.User.JID.Device)
  621. } else {
  622. ce.Reply("Logged in as +%s (device #%d), connection to WhatsApp OK (probably)", ce.User.JID.User, ce.User.JID.Device)
  623. }
  624. }
  625. const cmdHelpHelp = `help - Prints this help`
  626. // CommandHelp handles help command
  627. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  628. cmdPrefix := ""
  629. if ce.User.ManagementRoom != ce.RoomID {
  630. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  631. }
  632. ce.Reply("* " + strings.Join([]string{
  633. cmdPrefix + cmdHelpHelp,
  634. cmdPrefix + cmdVersionHelp,
  635. cmdPrefix + cmdLoginHelp,
  636. cmdPrefix + cmdLogoutHelp,
  637. cmdPrefix + cmdDeleteSessionHelp,
  638. cmdPrefix + cmdReconnectHelp,
  639. cmdPrefix + cmdDisconnectHelp,
  640. cmdPrefix + cmdPingHelp,
  641. cmdPrefix + cmdSetRelayHelp,
  642. cmdPrefix + cmdUnsetRelayHelp,
  643. cmdPrefix + cmdLoginMatrixHelp,
  644. cmdPrefix + cmdPingMatrixHelp,
  645. cmdPrefix + cmdLogoutMatrixHelp,
  646. cmdPrefix + cmdToggleHelp,
  647. cmdPrefix + cmdListHelp,
  648. cmdPrefix + cmdSearchHelp,
  649. cmdPrefix + cmdSyncHelp,
  650. cmdPrefix + cmdOpenHelp,
  651. cmdPrefix + cmdPMHelp,
  652. cmdPrefix + cmdInviteLinkHelp,
  653. cmdPrefix + cmdCheckInviteHelp,
  654. cmdPrefix + cmdJoinHelp,
  655. cmdPrefix + cmdCreateHelp,
  656. cmdPrefix + cmdSetPowerLevelHelp,
  657. cmdPrefix + cmdDeletePortalHelp,
  658. cmdPrefix + cmdDeleteAllPortalsHelp,
  659. }, "\n* "))
  660. }
  661. func canDeletePortal(portal *Portal, userID id.UserID) bool {
  662. members, err := portal.MainIntent().JoinedMembers(portal.MXID)
  663. if err != nil {
  664. portal.log.Errorfln("Failed to get joined members to check if portal can be deleted by %s: %v", userID, err)
  665. return false
  666. }
  667. for otherUser := range members.Joined {
  668. _, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
  669. if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
  670. continue
  671. }
  672. user := portal.bridge.GetUserByMXID(otherUser)
  673. if user != nil && user.Session != nil {
  674. return false
  675. }
  676. }
  677. return true
  678. }
  679. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  680. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  681. if ce.Portal == nil {
  682. ce.Reply("You must be in a portal room to use that command")
  683. return
  684. }
  685. if !ce.User.Admin && !canDeletePortal(ce.Portal, ce.User.MXID) {
  686. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  687. return
  688. }
  689. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  690. ce.Portal.Delete()
  691. ce.Portal.Cleanup(false)
  692. }
  693. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all portals.`
  694. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  695. portals := handler.bridge.GetAllPortals()
  696. var portalsToDelete []*Portal
  697. if ce.User.Admin {
  698. portalsToDelete = portals
  699. } else {
  700. portalsToDelete = portals[:0]
  701. for _, portal := range portals {
  702. if canDeletePortal(portal, ce.User.MXID) {
  703. portalsToDelete = append(portalsToDelete, portal)
  704. }
  705. }
  706. }
  707. leave := func(portal *Portal) {
  708. if len(portal.MXID) > 0 {
  709. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  710. Reason: "Deleting portal",
  711. UserID: ce.User.MXID,
  712. })
  713. }
  714. }
  715. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  716. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  717. intent := customPuppet.CustomIntent()
  718. leave = func(portal *Portal) {
  719. if len(portal.MXID) > 0 {
  720. _, _ = intent.LeaveRoom(portal.MXID)
  721. _, _ = intent.ForgetRoom(portal.MXID)
  722. }
  723. }
  724. }
  725. ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
  726. for _, portal := range portalsToDelete {
  727. portal.Delete()
  728. leave(portal)
  729. }
  730. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
  731. go func() {
  732. for _, portal := range portalsToDelete {
  733. portal.Cleanup(false)
  734. }
  735. ce.Reply("Finished background cleanup of deleted portal rooms.")
  736. }()
  737. }
  738. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  739. func matchesQuery(str string, query string) bool {
  740. if query == "" {
  741. return true
  742. }
  743. return strings.Contains(strings.ToLower(str), query)
  744. }
  745. func formatContacts(bridge *Bridge, input map[types.JID]types.ContactInfo, query string) (result []string) {
  746. hasQuery := len(query) > 0
  747. for jid, contact := range input {
  748. if len(contact.FullName) == 0 {
  749. continue
  750. }
  751. puppet := bridge.GetPuppetByJID(jid)
  752. pushName := contact.PushName
  753. if len(pushName) == 0 {
  754. pushName = contact.FullName
  755. }
  756. if !hasQuery || matchesQuery(pushName, query) || matchesQuery(contact.FullName, query) || matchesQuery(jid.User, query) {
  757. result = append(result, fmt.Sprintf("* %s / [%s](https://matrix.to/#/%s) - `+%s`", contact.FullName, pushName, puppet.MXID, jid.User))
  758. }
  759. }
  760. sort.Sort(sort.StringSlice(result))
  761. return
  762. }
  763. func formatGroups(input []*types.GroupInfo, query string) (result []string) {
  764. hasQuery := len(query) > 0
  765. for _, group := range input {
  766. if !hasQuery || matchesQuery(group.GroupName.Name, query) || matchesQuery(group.JID.User, query) {
  767. result = append(result, fmt.Sprintf("* %s - `%s`", group.GroupName.Name, group.JID.User))
  768. }
  769. }
  770. sort.Sort(sort.StringSlice(result))
  771. return
  772. }
  773. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  774. if len(ce.Args) == 0 {
  775. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  776. return
  777. }
  778. mode := strings.ToLower(ce.Args[0])
  779. if mode[0] != 'g' && mode[0] != 'c' {
  780. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  781. return
  782. }
  783. var err error
  784. page := 1
  785. max := 100
  786. if len(ce.Args) > 1 {
  787. page, err = strconv.Atoi(ce.Args[1])
  788. if err != nil || page <= 0 {
  789. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  790. return
  791. }
  792. }
  793. if len(ce.Args) > 2 {
  794. max, err = strconv.Atoi(ce.Args[2])
  795. if err != nil || max <= 0 {
  796. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  797. return
  798. } else if max > 400 {
  799. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  800. }
  801. }
  802. contacts := mode[0] == 'c'
  803. typeName := "Groups"
  804. var result []string
  805. if contacts {
  806. typeName = "Contacts"
  807. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  808. if err != nil {
  809. ce.Reply("Failed to get contacts: %s", err)
  810. return
  811. }
  812. result = formatContacts(ce.User.bridge, contactList, "")
  813. } else {
  814. groupList, err := ce.User.Client.GetJoinedGroups()
  815. if err != nil {
  816. ce.Reply("Failed to get groups: %s", err)
  817. return
  818. }
  819. result = formatGroups(groupList, "")
  820. }
  821. if len(result) == 0 {
  822. ce.Reply("No %s found", strings.ToLower(typeName))
  823. return
  824. }
  825. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  826. if (page-1)*max >= len(result) {
  827. if pages == 1 {
  828. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  829. } else {
  830. ce.Reply("There are %d pages of %s", pages, strings.ToLower(typeName))
  831. }
  832. return
  833. }
  834. lastIndex := page * max
  835. if lastIndex > len(result) {
  836. lastIndex = len(result)
  837. }
  838. result = result[(page-1)*max : lastIndex]
  839. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  840. }
  841. const cmdSearchHelp = `search <query> - Search for contacts or groups.`
  842. func (handler *CommandHandler) CommandSearch(ce *CommandEvent) {
  843. if len(ce.Args) == 0 {
  844. ce.Reply("**Usage:** `search <query>`")
  845. return
  846. }
  847. contactList, err := ce.User.Client.Store.Contacts.GetAllContacts()
  848. if err != nil {
  849. ce.Reply("Failed to get contacts: %s", err)
  850. return
  851. }
  852. groupList, err := ce.User.Client.GetJoinedGroups()
  853. if err != nil {
  854. ce.Reply("Failed to get groups: %s", err)
  855. return
  856. }
  857. query := strings.ToLower(strings.TrimSpace(strings.Join(ce.Args, " ")))
  858. formattedContacts := strings.Join(formatContacts(ce.User.bridge, contactList, query), "\n")
  859. formattedGroups := strings.Join(formatGroups(groupList, query), "\n")
  860. result := make([]string, 0, 2)
  861. if len(formattedContacts) > 0 {
  862. result = append(result, "### Contacts\n\n" + formattedContacts)
  863. }
  864. if len(formattedGroups) > 0 {
  865. result = append(result, "### Groups\n\n" + formattedGroups)
  866. }
  867. if len(result) == 0 {
  868. ce.Reply("No contacts or groups found")
  869. return
  870. }
  871. ce.Reply(strings.Join(result, "\n\n"))
  872. }
  873. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  874. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  875. if len(ce.Args) == 0 {
  876. ce.Reply("**Usage:** `open <group JID>`")
  877. return
  878. }
  879. var jid types.JID
  880. if strings.ContainsRune(ce.Args[0], '@') {
  881. jid, _ = types.ParseJID(ce.Args[0])
  882. } else {
  883. jid = types.NewJID(ce.Args[0], types.GroupServer)
  884. }
  885. if jid.Server != types.GroupServer || !strings.ContainsRune(jid.User, '-') {
  886. ce.Reply("That does not look like a group JID")
  887. return
  888. }
  889. info, err := ce.User.Client.GetGroupInfo(jid)
  890. if err != nil {
  891. ce.Reply("Failed to get group info: %v", err)
  892. return
  893. }
  894. handler.log.Debugln("Importing", jid, "for", ce.User.MXID)
  895. portal := ce.User.GetPortalByJID(info.JID)
  896. if len(portal.MXID) > 0 {
  897. portal.UpdateMatrixRoom(ce.User, info)
  898. ce.Reply("Portal room synced.")
  899. } else {
  900. err = portal.CreateMatrixRoom(ce.User, info, true)
  901. if err != nil {
  902. ce.Reply("Failed to create room: %v", err)
  903. } else {
  904. ce.Reply("Portal room created.")
  905. }
  906. }
  907. }
  908. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  909. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  910. if len(ce.Args) == 0 {
  911. ce.Reply("**Usage:** `pm <international phone number>`")
  912. return
  913. }
  914. user := ce.User
  915. number := strings.Join(ce.Args, "")
  916. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  917. if err != nil {
  918. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  919. return
  920. } else if len(resp) == 0 {
  921. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  922. return
  923. }
  924. targetUser := resp[0]
  925. if !targetUser.IsIn {
  926. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  927. return
  928. }
  929. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  930. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  931. puppet.SyncContact(user, true, "manual pm command")
  932. portal := user.GetPortalByJID(puppet.JID)
  933. if len(portal.MXID) > 0 {
  934. ok := portal.ensureUserInvited(user)
  935. if !ok {
  936. portal.log.Warnfln("ensureUserInvited(%s) returned false, creating new portal", user.MXID)
  937. portal.MXID = ""
  938. } else {
  939. ce.Reply("You already have a private chat portal with +%s at [%s](https://matrix.to/#/%s)", puppet.JID.User, puppet.Displayname, portal.MXID)
  940. return
  941. }
  942. }
  943. err = portal.CreateMatrixRoom(user, nil, false)
  944. if err != nil {
  945. ce.Reply("Failed to create portal room: %v", err)
  946. return
  947. }
  948. ce.Reply("Created portal room with +%s and invited you to it.", puppet.JID.User)
  949. }
  950. const cmdSyncHelp = `sync <appstate/contacts/groups> [--create-portals] - Synchronize data from WhatsApp.`
  951. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  952. if len(ce.Args) == 0 {
  953. ce.Reply("**Usage:** `sync <appstate/contacts/groups> [--create-portals]`")
  954. return
  955. }
  956. args := strings.ToLower(strings.Join(ce.Args, " "))
  957. contacts := strings.Contains(args, "contacts")
  958. appState := strings.Contains(args, "appstate")
  959. groups := strings.Contains(args, "groups")
  960. createPortals := strings.Contains(args, "--create-portals")
  961. if appState {
  962. for _, name := range appstate.AllPatchNames {
  963. err := ce.User.Client.FetchAppState(name, true, false)
  964. if err != nil {
  965. ce.Reply("Error syncing app state %s: %v", name, err)
  966. } else if name == appstate.WAPatchCriticalUnblockLow {
  967. ce.Reply("Synced app state %s, contact sync running in background", name)
  968. } else {
  969. ce.Reply("Synced app state %s", name)
  970. }
  971. }
  972. } else if contacts {
  973. err := ce.User.ResyncContacts()
  974. if err != nil {
  975. ce.Reply("Error resyncing contacts: %v", err)
  976. } else {
  977. ce.Reply("Resynced contacts")
  978. }
  979. }
  980. if groups {
  981. err := ce.User.ResyncGroups(createPortals)
  982. if err != nil {
  983. ce.Reply("Error resyncing groups: %v", err)
  984. } else {
  985. ce.Reply("Resynced groups")
  986. }
  987. }
  988. }
  989. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  990. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  991. if len(ce.Args) == 0 {
  992. ce.Reply("**Usage:** `login-matrix <access token>`")
  993. return
  994. }
  995. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  996. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  997. if err != nil {
  998. ce.Reply("Failed to switch puppet: %v", err)
  999. return
  1000. }
  1001. ce.Reply("Successfully switched puppet")
  1002. }
  1003. const cmdPingMatrixHelp = `ping-matrix - Check if your double puppet is working correctly.`
  1004. func (handler *CommandHandler) CommandPingMatrix(ce *CommandEvent) {
  1005. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1006. if puppet == nil || puppet.CustomIntent() == nil {
  1007. ce.Reply("You have not changed your WhatsApp account's Matrix puppet.")
  1008. return
  1009. }
  1010. resp, err := puppet.CustomIntent().Whoami()
  1011. if err != nil {
  1012. ce.Reply("Failed to validate Matrix login: %v", err)
  1013. } else {
  1014. ce.Reply("Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
  1015. }
  1016. }
  1017. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  1018. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  1019. puppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  1020. if puppet == nil || puppet.CustomIntent() == nil {
  1021. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  1022. return
  1023. }
  1024. err := puppet.SwitchCustomMXID("", "")
  1025. if err != nil {
  1026. ce.Reply("Failed to remove custom puppet: %v", err)
  1027. return
  1028. }
  1029. ce.Reply("Successfully removed custom puppet")
  1030. }