commands.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "fmt"
  19. "strconv"
  20. "strings"
  21. "github.com/Rhymen/go-whatsapp"
  22. "maunium.net/go/maulogger/v2"
  23. "maunium.net/go/mautrix"
  24. "maunium.net/go/mautrix-appservice"
  25. "maunium.net/go/mautrix/event"
  26. "maunium.net/go/mautrix/format"
  27. "maunium.net/go/mautrix/id"
  28. "maunium.net/go/mautrix-whatsapp/database"
  29. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  30. )
  31. type CommandHandler struct {
  32. bridge *Bridge
  33. log maulogger.Logger
  34. }
  35. // NewCommandHandler creates a CommandHandler
  36. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  37. return &CommandHandler{
  38. bridge: bridge,
  39. log: bridge.Log.Sub("Command handler"),
  40. }
  41. }
  42. // CommandEvent stores all data which might be used to handle commands
  43. type CommandEvent struct {
  44. Bot *appservice.IntentAPI
  45. Bridge *Bridge
  46. Handler *CommandHandler
  47. RoomID id.RoomID
  48. User *User
  49. Command string
  50. Args []string
  51. }
  52. // Reply sends a reply to command as notice
  53. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  54. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  55. content.MsgType = event.MsgNotice
  56. room := ce.User.ManagementRoom
  57. if len(room) == 0 {
  58. room = ce.RoomID
  59. }
  60. _, err := ce.Bot.SendMessageEvent(room, event.EventMessage, content)
  61. if err != nil {
  62. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  63. }
  64. }
  65. // Handle handles messages to the bridge
  66. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
  67. args := strings.Split(message, " ")
  68. ce := &CommandEvent{
  69. Bot: handler.bridge.Bot,
  70. Bridge: handler.bridge,
  71. Handler: handler,
  72. RoomID: roomID,
  73. User: user,
  74. Command: strings.ToLower(args[0]),
  75. Args: args[1:],
  76. }
  77. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  78. if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
  79. handler.CommandRelaybot(ce)
  80. } else {
  81. handler.CommandMux(ce)
  82. }
  83. }
  84. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  85. switch ce.Command {
  86. case "relaybot":
  87. handler.CommandRelaybot(ce)
  88. case "login":
  89. handler.CommandLogin(ce)
  90. case "logout-matrix":
  91. handler.CommandLogoutMatrix(ce)
  92. case "help":
  93. handler.CommandHelp(ce)
  94. case "reconnect":
  95. handler.CommandReconnect(ce)
  96. case "disconnect":
  97. handler.CommandDisconnect(ce)
  98. case "ping":
  99. handler.CommandPing(ce)
  100. case "delete-connection":
  101. handler.CommandDeleteConnection(ce)
  102. case "delete-session":
  103. handler.CommandDeleteSession(ce)
  104. case "delete-portal":
  105. handler.CommandDeletePortal(ce)
  106. case "delete-all-portals":
  107. handler.CommandDeleteAllPortals(ce)
  108. case "dev-test":
  109. handler.CommandDevTest(ce)
  110. case "set-pl":
  111. handler.CommandSetPowerLevel(ce)
  112. case "login-matrix", "logout", "sync", "list", "open", "pm":
  113. if !ce.User.HasSession() {
  114. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  115. return
  116. } else if !ce.User.IsConnected() {
  117. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  118. return
  119. }
  120. switch ce.Command {
  121. case "login-matrix":
  122. handler.CommandLoginMatrix(ce)
  123. case "logout":
  124. handler.CommandLogout(ce)
  125. case "sync":
  126. handler.CommandSync(ce)
  127. case "list":
  128. handler.CommandList(ce)
  129. case "open":
  130. handler.CommandOpen(ce)
  131. case "pm":
  132. handler.CommandPM(ce)
  133. }
  134. default:
  135. ce.Reply("Unknown Command")
  136. }
  137. }
  138. func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
  139. if handler.bridge.Relaybot == nil {
  140. ce.Reply("The relaybot is disabled")
  141. } else if !ce.User.Admin {
  142. ce.Reply("Only admins can manage the relaybot")
  143. } else {
  144. if ce.Command == "relaybot" {
  145. if len(ce.Args) == 0 {
  146. ce.Reply("**Usage:** `relaybot <command>`")
  147. return
  148. }
  149. ce.Command = strings.ToLower(ce.Args[0])
  150. ce.Args = ce.Args[1:]
  151. }
  152. ce.User = handler.bridge.Relaybot
  153. handler.CommandMux(ce)
  154. }
  155. }
  156. func (handler *CommandHandler) CommandDevTest(ce *CommandEvent) {
  157. }
  158. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  159. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  160. if portal == nil {
  161. ce.Reply("Not a portal room")
  162. return
  163. }
  164. var level int
  165. var userID id.UserID
  166. var err error
  167. if len(ce.Args) == 1 {
  168. level, err = strconv.Atoi(ce.Args[0])
  169. if err != nil {
  170. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  171. return
  172. }
  173. userID = ce.User.MXID
  174. } else if len(ce.Args) == 2 {
  175. userID = id.UserID(ce.Args[0])
  176. _, _, err := userID.Parse()
  177. if err != nil {
  178. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  179. return
  180. }
  181. level, err = strconv.Atoi(ce.Args[1])
  182. if err != nil {
  183. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  184. return
  185. }
  186. } else {
  187. ce.Reply("**Usage:** `set-pl [user] <level>`")
  188. return
  189. }
  190. intent := portal.MainIntent()
  191. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  192. if err != nil {
  193. ce.Reply("Failed to set power levels: %v", err)
  194. }
  195. }
  196. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  197. // CommandLogin handles login command
  198. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  199. if !ce.User.Connect(true) {
  200. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  201. return
  202. }
  203. ce.User.Login(ce)
  204. }
  205. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  206. // CommandLogout handles !logout command
  207. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  208. if ce.User.Session == nil {
  209. ce.Reply("You're not logged in.")
  210. return
  211. }
  212. err := ce.User.Conn.Logout()
  213. if err != nil {
  214. ce.User.log.Warnln("Error while logging out:", err)
  215. ce.Reply("Unknown error while logging out: %v", err)
  216. return
  217. }
  218. _, err = ce.User.Conn.Disconnect()
  219. if err != nil {
  220. ce.User.log.Warnln("Error while disconnecting after logout:", err)
  221. }
  222. ce.User.Conn.RemoveHandlers()
  223. ce.User.Conn = nil
  224. ce.User.SetSession(nil)
  225. ce.Reply("Logged out successfully.")
  226. }
  227. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  228. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  229. if ce.User.Session == nil && ce.User.Conn == nil {
  230. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  231. return
  232. }
  233. ce.User.SetSession(nil)
  234. if ce.User.Conn != nil {
  235. _, _ = ce.User.Conn.Disconnect()
  236. ce.User.Conn.RemoveHandlers()
  237. ce.User.Conn = nil
  238. }
  239. ce.Reply("Session information purged")
  240. }
  241. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  242. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  243. if ce.User.Conn == nil {
  244. if ce.User.Session == nil {
  245. ce.Reply("No existing connection and no session. Did you mean `login`?")
  246. } else {
  247. ce.Reply("No existing connection, creating one...")
  248. ce.User.Connect(false)
  249. }
  250. return
  251. }
  252. wasConnected := true
  253. sess, err := ce.User.Conn.Disconnect()
  254. if err == whatsapp.ErrNotConnected {
  255. wasConnected = false
  256. } else if err != nil {
  257. ce.User.log.Warnln("Error while disconnecting:", err)
  258. } else if len(sess.Wid) > 0 {
  259. ce.User.SetSession(&sess)
  260. }
  261. err = ce.User.Conn.Restore()
  262. if err == whatsapp.ErrInvalidSession {
  263. if ce.User.Session != nil {
  264. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  265. var sess whatsapp.Session
  266. sess, err = ce.User.Conn.RestoreWithSession(*ce.User.Session)
  267. if err == nil {
  268. ce.User.SetSession(&sess)
  269. }
  270. } else {
  271. ce.Reply("You are not logged in.")
  272. return
  273. }
  274. } else if err == whatsapp.ErrLoginInProgress {
  275. ce.Reply("A login or reconnection is already in progress.")
  276. return
  277. } else if err == whatsapp.ErrAlreadyLoggedIn {
  278. ce.Reply("You were already connected.")
  279. return
  280. }
  281. if err != nil {
  282. ce.User.log.Warnln("Error while reconnecting:", err)
  283. if err.Error() == "restore session connection timed out" {
  284. ce.Reply("Reconnection timed out. Is WhatsApp on your phone reachable?")
  285. } else {
  286. ce.Reply("Unknown error while reconnecting: %v", err)
  287. }
  288. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  289. sess, err := ce.User.Conn.Disconnect()
  290. if err != nil {
  291. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  292. } else if len(sess.Wid) > 0 {
  293. ce.User.SetSession(&sess)
  294. }
  295. return
  296. }
  297. ce.User.ConnectionErrors = 0
  298. var msg string
  299. if wasConnected {
  300. msg = "Reconnected successfully."
  301. } else {
  302. msg = "Connected successfully."
  303. }
  304. ce.Reply(msg)
  305. ce.User.PostLogin()
  306. }
  307. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  308. if ce.User.Conn == nil {
  309. ce.Reply("You don't have a WhatsApp connection.")
  310. return
  311. }
  312. sess, err := ce.User.Conn.Disconnect()
  313. if err == nil && len(sess.Wid) > 0 {
  314. ce.User.SetSession(&sess)
  315. }
  316. ce.User.Conn.RemoveHandlers()
  317. ce.User.Conn = nil
  318. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  319. }
  320. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  321. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  322. if ce.User.Conn == nil {
  323. ce.Reply("You don't have a WhatsApp connection.")
  324. return
  325. }
  326. sess, err := ce.User.Conn.Disconnect()
  327. if err == whatsapp.ErrNotConnected {
  328. ce.Reply("You were not connected.")
  329. return
  330. } else if err != nil {
  331. ce.User.log.Warnln("Error while disconnecting:", err)
  332. ce.Reply("Unknown error while disconnecting: %v", err)
  333. return
  334. } else if len(sess.Wid) > 0 {
  335. ce.User.SetSession(&sess)
  336. }
  337. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  338. }
  339. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  340. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  341. if ce.User.Session == nil {
  342. if ce.User.IsLoginInProgress() {
  343. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  344. } else {
  345. ce.Reply("You're not logged into WhatsApp.")
  346. }
  347. } else if ce.User.Conn == nil {
  348. ce.Reply("You don't have a WhatsApp connection.")
  349. } else if ok, err := ce.User.Conn.AdminTest(); err != nil {
  350. if ce.User.IsLoginInProgress() {
  351. ce.Reply("Connection not OK: %v, but login in progress", err)
  352. } else {
  353. ce.Reply("Connection not OK: %v", err)
  354. }
  355. } else if !ok {
  356. if ce.User.IsLoginInProgress() {
  357. ce.Reply("Connection not OK, but no error received and login in progress")
  358. } else {
  359. ce.Reply("Connection not OK, but no error received")
  360. }
  361. } else {
  362. ce.Reply("Connection to WhatsApp OK")
  363. }
  364. }
  365. const cmdHelpHelp = `help - Prints this help`
  366. // CommandHelp handles help command
  367. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  368. cmdPrefix := ""
  369. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  370. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  371. }
  372. ce.Reply("* " + strings.Join([]string{
  373. cmdPrefix + cmdHelpHelp,
  374. cmdPrefix + cmdLoginHelp,
  375. cmdPrefix + cmdLogoutHelp,
  376. cmdPrefix + cmdDeleteSessionHelp,
  377. cmdPrefix + cmdReconnectHelp,
  378. cmdPrefix + cmdDisconnectHelp,
  379. cmdPrefix + cmdPingHelp,
  380. cmdPrefix + cmdLoginMatrixHelp,
  381. cmdPrefix + cmdLogoutMatrixHelp,
  382. cmdPrefix + cmdSyncHelp,
  383. cmdPrefix + cmdListHelp,
  384. cmdPrefix + cmdOpenHelp,
  385. cmdPrefix + cmdPMHelp,
  386. }, "\n* "))
  387. }
  388. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  389. // CommandSync handles sync command
  390. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  391. user := ce.User
  392. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  393. ce.Reply("Updating contact and chat list...")
  394. handler.log.Debugln("Importing contacts of", user.MXID)
  395. _, err := user.Conn.Contacts()
  396. if err != nil {
  397. user.log.Errorln("Error updating contacts:", err)
  398. ce.Reply("Failed to sync contact list (see logs for details)")
  399. return
  400. }
  401. handler.log.Debugln("Importing chats of", user.MXID)
  402. _, err = user.Conn.Chats()
  403. if err != nil {
  404. user.log.Errorln("Error updating chats:", err)
  405. ce.Reply("Failed to sync chat list (see logs for details)")
  406. return
  407. }
  408. ce.Reply("Syncing contacts...")
  409. user.syncPuppets(nil)
  410. ce.Reply("Syncing chats...")
  411. user.syncPortals(nil, create)
  412. ce.Reply("Sync complete.")
  413. }
  414. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  415. if !ce.User.Admin {
  416. ce.Reply("Only bridge admins can delete portals")
  417. return
  418. }
  419. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  420. if portal == nil {
  421. ce.Reply("You must be in a portal room to use that command")
  422. return
  423. }
  424. portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  425. portal.Delete()
  426. portal.Cleanup(false)
  427. }
  428. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  429. portals := ce.User.GetPortals()
  430. portalsToDelete := make([]*Portal, 0, len(portals))
  431. for _, portal := range portals {
  432. users := portal.GetUserIDs()
  433. if len(users) == 1 && users[0] == ce.User.MXID {
  434. portalsToDelete = append(portalsToDelete, portal)
  435. }
  436. }
  437. leave := func(portal *Portal) {
  438. if len(portal.MXID) > 0 {
  439. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  440. Reason: "Deleting portal",
  441. UserID: ce.User.MXID,
  442. })
  443. }
  444. }
  445. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  446. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  447. intent := customPuppet.CustomIntent()
  448. leave = func(portal *Portal) {
  449. if len(portal.MXID) > 0 {
  450. _, _ = intent.LeaveRoom(portal.MXID)
  451. _, _ = intent.ForgetRoom(portal.MXID)
  452. }
  453. }
  454. }
  455. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  456. for _, portal := range portalsToDelete {
  457. portal.Delete()
  458. leave(portal)
  459. }
  460. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  461. "You may already continue using the bridge. Use `sync` to recreate portals.")
  462. go func() {
  463. for _, portal := range portalsToDelete {
  464. portal.Cleanup(false)
  465. }
  466. ce.Reply("Finished background cleanup of deleted portal rooms.")
  467. }()
  468. }
  469. const cmdListHelp = `list - Get a list of all contacts and groups.`
  470. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  471. var contacts strings.Builder
  472. var groups strings.Builder
  473. for jid, contact := range ce.User.Conn.Store.Contacts {
  474. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  475. _, _ = fmt.Fprintf(&contacts, "* %s / %s - `%s`\n", contact.Name, contact.Notify, contact.Jid[:len(contact.Jid)-len(whatsappExt.NewUserSuffix)])
  476. } else {
  477. _, _ = fmt.Fprintf(&groups, "* %s - `%s`\n", contact.Name, contact.Jid)
  478. }
  479. }
  480. ce.Reply("### Contacts\n%s\n\n### Groups\n%s", contacts.String(), groups.String())
  481. }
  482. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  483. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  484. if len(ce.Args) == 0 {
  485. ce.Reply("**Usage:** `open <group JID>`")
  486. return
  487. }
  488. user := ce.User
  489. jid := ce.Args[0]
  490. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  491. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)])
  492. return
  493. }
  494. contact, ok := user.Conn.Store.Contacts[jid]
  495. if !ok {
  496. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  497. return
  498. }
  499. handler.log.Debugln("Importing", jid, "for", user)
  500. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  501. if len(portal.MXID) > 0 {
  502. portal.Sync(user, contact)
  503. ce.Reply("Portal room synced.")
  504. } else {
  505. portal.Sync(user, contact)
  506. ce.Reply("Portal room created.")
  507. }
  508. }
  509. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  510. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  511. if len(ce.Args) == 0 {
  512. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  513. return
  514. }
  515. force := ce.Args[0] == "--force"
  516. if force {
  517. ce.Args = ce.Args[1:]
  518. }
  519. user := ce.User
  520. number := strings.Join(ce.Args, "")
  521. if number[0] == '+' {
  522. number = number[1:]
  523. }
  524. for _, char := range number {
  525. if char < '0' || char > '9' {
  526. ce.Reply("Invalid phone number.")
  527. return
  528. }
  529. }
  530. jid := number + whatsappExt.NewUserSuffix
  531. handler.log.Debugln("Importing", jid, "for", user)
  532. contact, ok := user.Conn.Store.Contacts[jid]
  533. if !ok {
  534. if !force {
  535. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  536. "To create a portal anyway, use `pm --force <number>`.")
  537. return
  538. }
  539. contact = whatsapp.Contact{Jid: jid}
  540. }
  541. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  542. puppet.Sync(user, contact)
  543. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
  544. if len(portal.MXID) > 0 {
  545. _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  546. if err != nil {
  547. fmt.Println(err)
  548. } else {
  549. ce.Reply("Existing portal room found, invited you to it.")
  550. }
  551. return
  552. }
  553. err := portal.CreateMatrixRoom(user)
  554. if err != nil {
  555. ce.Reply("Failed to create portal room: %v", err)
  556. return
  557. }
  558. ce.Reply("Created portal room and invited you to it.")
  559. }
  560. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  561. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  562. if len(ce.Args) == 0 {
  563. ce.Reply("**Usage:** `login-matrix <access token>`")
  564. return
  565. }
  566. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  567. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  568. if err != nil {
  569. ce.Reply("Failed to switch puppet: %v", err)
  570. return
  571. }
  572. ce.Reply("Successfully switched puppet")
  573. }
  574. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  575. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  576. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  577. if len(puppet.CustomMXID) == 0 {
  578. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  579. return
  580. }
  581. err := puppet.SwitchCustomMXID("", "")
  582. if err != nil {
  583. ce.Reply("Failed to remove custom puppet: %v", err)
  584. return
  585. }
  586. ce.Reply("Successfully removed custom puppet")
  587. }