SnapEnhance icon indicating copy to clipboard operation
SnapEnhance copied to clipboard

Messaging Module not working correctly

Open particle-box opened this issue 1 year ago • 2 comments

Description

The messaging module isn't working correctly anymore. [Attached logs]

Reproduction steps

  1. Go to ...
  2. Click on ....
  3. Scroll down to ....
  4. See error.

Logs

|D/2024-07-29 15:37:01/manager/Failed to enable script. Check logs for more details
|E/2024-07-29 15:37:01/manager/org.mozilla.javascript.EcmaError: TypeError: Cannot call method "onConversationUpdated" of null (SourceFile#2)
	at org.mozilla.javascript.ScriptRuntime.constructError(SourceFile:9)
	at org.mozilla.javascript.ScriptRuntime.constructError(SourceFile:3)
	at org.mozilla.javascript.ScriptRuntime.typeError(Unknown Source:2)
	at org.mozilla.javascript.ScriptRuntime.typeErrorById(Unknown Source:4)
	at org.mozilla.javascript.ScriptRuntime.undefCallError(Unknown Source:14)
	at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(Unknown Source:42)
	at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(SourceFile:3)
	at org.mozilla.javascript.gen.auto_reply_6._c_start_26(auto_reply:167)
	at org.mozilla.javascript.gen.auto_reply_6.call(Unknown Source:198)
	at org.mozilla.javascript.optimizer.OptRuntime.callName0(Unknown Source:10)
	at org.mozilla.javascript.gen.auto_reply_6._c_anonymous_1(auto_reply:185)
	at org.mozilla.javascript.gen.auto_reply_6.call(Unknown Source:41)
	at org.mozilla.javascript.optimizer.OptRuntime.call0(Unknown Source:2)
	at org.mozilla.javascript.gen.auto_reply_6._c_script_0(auto_reply:186)
	at org.mozilla.javascript.gen.auto_reply_6.call(Unknown Source:35)
	at org.mozilla.javascript.ContextFactory.doTopCall(Unknown Source:0)
	at org.mozilla.javascript.ScriptRuntime.doTopCall(SourceFile:8)
	at org.mozilla.javascript.gen.auto_reply_6.call(Unknown Source:18)
	at org.mozilla.javascript.gen.auto_reply_6.exec(Unknown Source:10)
	at org.mozilla.javascript.Context.evaluateReader(Unknown Source:6)
	at me.rhunk.snapenhance.common.scripting.JSModule.load$lambda$49(Unknown Source:26)
	at me.rhunk.snapenhance.common.scripting.JSModule.c(Unknown Source:0)
	at a3.g.invoke(Unknown Source:31)
	at me.rhunk.snapenhance.common.scripting.ktx.RhinoKtxKt.contextScope(Unknown Source:88)
	at me.rhunk.snapenhance.common.scripting.JSModule.load(Unknown Source:22)
	at me.rhunk.snapenhance.common.scripting.ScriptRuntime.load(SourceFile:10)
	at me.rhunk.snapenhance.common.scripting.ScriptRuntime.load(SourceFile:2)
	at me.rhunk.snapenhance.scripting.RemoteScriptManager.loadScript(Unknown Source:14)
	at me.rhunk.snapenhance.ui.manager.pages.scripting.ScriptingRootSection$ModuleItem$3$2$3$1.invokeSuspend(Unknown Source:106)
	at v2.a.resumeWith(Unknown Source:8)
	at P2.H.run(Unknown Source:114)
	at P2.u0.run(Unknown Source:102)
	at W2.j.run(Unknown Source:2)
	at W2.b.run(Unknown Source:95)

|V/2024-07-29 15:37:10/manager/checking for updates for message_bomber null
|V/2024-07-29 15:37:10/manager/checking for updates for saved_replies null
|V/2024-07-29 15:37:10/manager/checking for updates for custom_reminders null
|V/2024-07-29 15:37:10/manager/checking for updates for greetings_toast null
|V/2024-07-29 15:37:10/manager/checking for updates for motivation_dialogs null
|V/2024-07-29 15:37:10/manager/checking for updates for motivation_dialogs null
|V/2024-07-29 15:37:10/manager/checking for updates for custom_toast null
|V/2024-07-29 15:37:10/manager/checking for updates for all_modules_availability_check null
|V/2024-07-29 15:37:10/manager/checking for updates for conversation_id_logger null
|V/2024-07-29 15:37:10/manager/checking for updates for auto_reply null
|V/2024-07-29 15:37:10/manager/checking for updates for scheduled_message null
|I/2024-07-29 15:37:11/Scripting/Loading module auto-reply-script (1).js
|E/2024-07-29 15:37:11/manager/Failed to enable script. Check logs for more details
|D/2024-07-29 15:37:11/manager/Failed to enable script. Check logs for more details
|E/2024-07-29 15:37:11/manager/org.mozilla.javascript.EcmaError: TypeError: Cannot call method "onConversationUpdated" of null (SourceFile#2)
	at org.mozilla.javascript.ScriptRuntime.constructError(SourceFile:9)
	at org.mozilla.javascript.ScriptRuntime.constructError(SourceFile:3)
	at org.mozilla.javascript.ScriptRuntime.typeError(Unknown Source:2)
	at org.mozilla.javascript.ScriptRuntime.typeErrorById(Unknown Source:4)
	at org.mozilla.javascript.ScriptRuntime.undefCallError(Unknown Source:14)
	at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThisHelper(Unknown Source:42)
	at org.mozilla.javascript.ScriptRuntime.getPropFunctionAndThis(SourceFile:3)
	at org.mozilla.javascript.gen.auto_reply_7._c_start_26(auto_reply:167)
	at org.mozilla.javascript.gen.auto_reply_7.call(Unknown Source:198)
	at org.mozilla.javascript.optimizer.OptRuntime.callName0(Unknown Source:10)
	at org.mozilla.javascript.gen.auto_reply_7._c_anonymous_1(auto_reply:185)
	at org.mozilla.javascript.gen.auto_reply_7.call(Unknown Source:41)
	at org.mozilla.javascript.optimizer.OptRuntime.call0(Unknown Source:2)
	at org.mozilla.javascript.gen.auto_reply_7._c_script_0(auto_reply:186)
	at org.mozilla.javascript.gen.auto_reply_7.call(Unknown Source:35)
	at org.mozilla.javascript.ContextFactory.doTopCall(Unknown Source:0)
	at org.mozilla.javascript.ScriptRuntime.doTopCall(SourceFile:8)
	at org.mozilla.javascript.gen.auto_reply_7.call(Unknown Source:18)
	at org.mozilla.javascript.gen.auto_reply_7.exec(Unknown Source:10)
	at org.mozilla.javascript.Context.evaluateReader(Unknown Source:6)
	at me.rhunk.snapenhance.common.scripting.JSModule.load$lambda$49(Unknown Source:26)
	at me.rhunk.snapenhance.common.scripting.JSModule.c(Unknown Source:0)
	at a3.g.invoke(Unknown Source:31)
	at me.rhunk.snapenhance.common.scripting.ktx.RhinoKtxKt.contextScope(Unknown Source:88)
	at me.rhunk.snapenhance.common.scripting.JSModule.load(Unknown Source:22)
	at me.rhunk.snapenhance.common.scripting.ScriptRuntime.load(SourceFile:10)
	at me.rhunk.snapenhance.common.scripting.ScriptRuntime.load(SourceFile:2)
	at me.rhunk.snapenhance.scripting.RemoteScriptManager.loadScript(Unknown Source:14)
	at me.rhunk.snapenhance.ui.manager.pages.scripting.ScriptingRootSection$ModuleItem$3$2$3$1.invokeSuspend(Unknown Source:106)
	at v2.a.resumeWith(Unknown Source:8)
	at P2.H.run(Unknown Source:114)
	at P2.u0.run(Unknown Source:102)
	at W2.j.run(Unknown Source:2)
	at W2.b.run(Unknown Source:95)

Snapchat Version

13.1.0.37

SnapEnhance Version

Latest CI Build

Agreement

  • [X] This is not a bug regarding Snapchat+.
  • [X] I have provided a detailed description of the issue.
  • [X] I have attached a log if deemed necessary.
  • [X] This issue is not a duplicate.

particle-box avatar Jul 29 '24 10:07 particle-box

Someone has already had this problem, you can take a look at this issue : https://github.com/SnapEnhance/docs/issues/2. I hope it helps

rhunk avatar Jul 29 '24 14:07 rhunk

Someone has already had this problem, you can take a look at this issue : SnapEnhance/docs#2. I hope it helps

Thank you for your response. As mentioned there, I followed all the steps mentioned and incorporated it in the reply_with_ai.js script as an example. It still throws error. Logs: log.txt (check after |V/2024-07-29 22:56:09/manager/Syncing remote took 73 ms) The code of the modified script for better understanding of the issue:

// ==SE_module==
// name: replay_with_ai_beta
// displayName: AI Respond
// description: A straightforward AI for automatic responses to your friends
// version: 3.0
// author: Suleyman Laarabi
// ==/SE_module==

var networking = require("networking");
var messaging = require("messaging");
var config = require("config");
var im = require("interface-manager");
var ipc = require("ipc");
var javaInterfaces = require("java-interfaces");
var hooker = require("hooker");
var events = require("events");

(function () {
    'use strict';

    var conversationToolboxContext = {
        events: [],
    };

    var languages = [
        "English",
        "French",
        "Spanish",
        "German",
        "Italian",
        "Hindi",
        "Dutch",
    ];

    var myAISenderID = "4adc8a6c-2b7b-51a1-a342-67513abbd33e";

    var settingsContext = {
        events: [],
    };

    var defaultPrompt = "Conversation with a friend. \n <listMessages> Write a respond to: <myLastMessage>, IN <language> !. Do not refer to your AI capabilities !. If the conversation slows down, continue with a relevant question or comment. your answer must be short.";

    function createManagerToolBoxUI() {
        settingsContext.events.push({
            start: function (builder) {
                var oldSelectedLanguage = getSelectedLanguage();
                builder.row(function (builder) {
                    var text = builder.text("Language :" + oldSelectedLanguage);
                    builder.slider(0, languages.length - 1, languages.length - 2, config.getInteger("languageAI", 0), function (value) {
                        text.label("Language :" + languages[value]);
                        config.setInteger("languageAI", value, true);
                    });
                });
                builder.row(function (builder) {
                    builder.button("Clear Config", function () {
                        config.set("customPrompt", defaultPrompt, true);
                        config.setInteger("languageAI", 0, true);
                    });
                });
                builder.row(function (builder) {
                    builder
                        .textInput("Custom Prompt", config.get("customPrompt", defaultPrompt), function (value) {
                        config.set("customPrompt", value, true);
                    })
                        .maxLines(8)
                        .singleLine(false);
                });
            },
        });
    }

    function getMyUserId(context) {
        var database = context.openOrCreateDatabase("arroyo.db", 0, null);
        var cursor = database.rawQuery("SELECT value FROM required_values WHERE key = 'USERID'", null);
        try {
            if (cursor.moveToFirst()) {
                return cursor.getString(0);
            }
        }
        finally {
            cursor.close();
            database.close();
        }
        return null;
    }

    var snapActivityContext = {
        activity: null,
        events: [],
    };

    function toOnlyValidMessages(messageList) {
        var userId = getMyUserId(snapActivityContext.activity);
        var validMessages = [];
        messageList.forEach(function (message) {
            var serializedMessage = message.serialize();
            if (serializedMessage != null) {
                validMessages.push({
                    sender: message.senderId.toString() == userId ? "a" : "b",
                    senderDisplay: message.senderId.toString() == userId
                        ? "(moi)"
                        : "autre personne (repond a lui)",
                    message: serializedMessage,
                });
            }
        });
        return validMessages;
    }

    function getLatestMessages(conversationId, callback) {
        messaging.fetchConversationWithMessages(conversationId, function (error, messageList) { return callback(toOnlyValidMessages(messageList)); });
    }

    function getMyAIResponse(prompt, callback) {
        messaging.getOneOnOneConversationIds([myAISenderID], function (error, result) {
            var myAIConversationID = result[0].conversationId;
            messaging.sendChatMessage(myAIConversationID, prompt, function () {
                sleep(4100);
                messaging.fetchConversationWithMessages(myAIConversationID, function (error, result) {
                    var lastMessage = result[result.length - 1].serialize();
                    callback(lastMessage);
                });
            });
        });
    }

    function getAiResponse(conversationId, onResponseCallBack) {
        getLatestMessages(conversationId, function (messageList) {
            var lastMessageFromB = messageList
                .slice()
                .reverse()
                .filter(function (msg) { return msg.sender === "b"; })[0];
            var context = messageList.slice(Math.max(messageList.length - 8, 0), messageList.length - 1);
            var listMessages = context
                .map(function (msg) { return "".concat(msg.sender, ": ").concat(msg.message); })
                .join("\n");
            var myLastMessage = lastMessageFromB.message;
            var prompt = config
                .get("customPrompt", defaultPrompt)
                .replace("<myLastMessage>", myLastMessage)
                .replace("<listMessages>", listMessages)
                .replace("<language>", getSelectedLanguage());
            getMyAIResponse(prompt, onResponseCallBack);
        });
    }

    function waitForMessaging(callback) {
    type("java.lang.Thread").newInstance(
        interfaces.runnable(() => {
            try {
                while (!messaging.isPresent()) {
                    type("java.lang.Thread").sleep(100);
                }
                callback();
            } catch (e) {
                logError(e);
            }
        })
    ).start();}

    function replyWithAI(conversationId) {
        waitForMessaging(function() {
            getAiResponse(conversationId, function (response) {
                messaging.sendChatMessage(conversationId, response, function () {
                    ipc.emit("aiResponseSent", { conversationId: conversationId, response: response });
                });
            });
        });
    }

    function getSelectedLanguage() {
        return languages[config.getInteger("languageAI", 1)];
    }

    function createConversationToolboxUI() {
        conversationToolboxContext.events.push({
            start: function (builder, args) {
                builder.button("Send reply in " + getSelectedLanguage(), function () {
                    getAiResponse(args["conversationId"], function (response) {
                        messaging.sendChatMessage(args["conversationId"], response, function () { });
                    });
                });
            },
        });
    }

    var friendFeedContext = {
        events: [],
    };

    function getIfUseAutoReply(conversationId) {
        var configID = "useAutoReply-" + conversationId;
        return config.getBoolean(configID, false);
    }

    function createFriendFeedToolBoxUI() {
        friendFeedContext.events.push({
            start: function (builder, args) {
                var conversationId = args["conversationId"];
                var configID = "useAutoReply-" + conversationId;
                builder
                    .row(function (builder) {
                    builder.text("Use auto reply");
                    builder.switch(config.getBoolean(configID, false), function (value) {
                        config.setBoolean(configID, value, true);
                    });
                })
                    .arrangement("spaceBetween")
                    .fillMaxWidth()
                    .padding(4);
            },
        });
    }

    function createInterface() {
        createConversationToolboxUI();
        createManagerToolBoxUI();
        createFriendFeedToolBoxUI();
    }

    function initAutoReply() {
        snapActivityContext.events.push({
            start: function (activity) {
                var myUserId = getMyUserId(activity);
                var messageAlreadyReply = [];
                events.onConversationUpdated(function (update) {
                    var message = update.messages[0];
                    if (!message && !message.messageDescriptor)
                        return;
                    var conversationId = message.messageDescriptor.conversationId;
                    var messageType = message.messageContent.contentType;
                    if (messageType == "CHAT" || messageType == "NOTE") {
                        if (message.senderId.toString() != myUserId) {
                            var isAlreadySend_1 = false;
                            messageAlreadyReply.forEach(function (id) {
                                if (id == message.messageDescriptor.messageId) {
                                    isAlreadySend_1 = true;
                                }
                            });
                            if (!isAlreadySend_1) {
                                var useAutoReply = JSON.parse("" + getIfUseAutoReply(conversationId.toString()));
                                if (useAutoReply) {
                                    if (messageType == "NOTE") {
                                        var language = getSelectedLanguage();
                                        waitForMessaging(function() {
                                            getMyAIResponse("Write in " +
                                                language +
                                                " A response to indicate that we cannot listen and ask the user to write, please provide me just the response text", function (response) {
                                                messaging.sendChatMessage(conversationId.toString(), response, function () {
                                                    ipc.emit("aiResponseSent", { conversationId: conversationId.toString(), response: response });
                                                });
                                            });
                                        });
                                        return;
                                    }
                                    replyWithAI(conversationId.toString());
                                }
                                messageAlreadyReply.push(message.messageDescriptor.messageId);
                            }
                        }
                    }
                });
            },
        });
    }

    function start(_) {
        createInterface();
        initAutoReply();
    }

    var snapApplicationContext = {
        context: null,
        events: [],
    };

    var snapEnhancerContext = {
        context: null,
        events: [],
    };

    var unloadContext = {
        events: [],
    };

    start();
    module.onSnapMainActivityCreate = function (activity) {
        snapActivityContext.activity = activity;
        snapActivityContext.events.forEach(function (event) {
            event.start(activity, null);
        });
    };
    module.onSnapApplicationLoad = function (context) {
        snapApplicationContext.context = context;
        snapApplicationContext.events.forEach(function (event) {
            event.start(context, null);
        });
    };
    module.onSnapEnhanceLoad = function (context) {
        snapEnhancerContext.context = context;
        snapEnhancerContext.events.forEach(function (event) {
            event.start(context, null);
        });
    };
    module.onUnload = function () {
        unloadContext.events.forEach(function (event) {
            event.start(null, null);
        });
    };
    im.create("conversationToolbox", function (builder, args) {
        conversationToolboxContext.events.forEach(function (event) {
            event.start(builder, args);
        });
    });
    im.create("friendFeedContextMenu", function (builder, args) {
        friendFeedContext.events.forEach(function (event) {
            event.start(builder, args);
        });
    });
    im.create("settings", function (builder, args) {
        settingsContext.events.forEach(function (event) {
            event.start(builder, args);
        });
    });

})();

**Main changes that I made:

  1. The waitForMessaging function uses a thread to wait for the messaging module to be present.
  2. I modified the replyWithAI and initAutoReply functions that use waitForMessaging.
  3. IPC event after sending messages.**

particle-box avatar Jul 29 '24 17:07 particle-box