【问题标题】:The bot for VK answers in a private messages, and not in a conversationVK 的机器人在私人消息中回答,而不是在对话中
【发布时间】:2021-03-25 23:46:32
【问题描述】:

我正在创建一个参考机器人,用于使用回调 Api 在 Python 中的 VK 中聊天。如果您写入群组消息,机器人将正常工作。但是,如果您写入对话(添加了机器人),它会回复私人消息。发布的所有阅读等权利。据我了解(在互联网上研究信息),我使用user_id,而不是chat_id。但我不明白如何正确修复它(

附言建议机器人在私人消息和对话中都写,这取决于他们问的地方。

p.p.s 或许这个问题看起来很可笑,但是我刚开始研究这个领域,我在网上没有找到答案:-)

机器人本身:

import vk
import random
import messageHandler

@ app.route ('/', methods = ['POST'])
def processing ():
    data = json.loads (request.data)
    if 'type' not in data.keys ():
        return 'not vk'
    if data ['type'] == 'confirmation':
        return confirmation_token
    elif data ['type'] == 'message_new':
        messageHandler.create_answer (data ['object'] ['message'], token)
        return 'ok'

“响应者”:

import importlib
from command_system import command_list

def load_modules ():
   # path from the working directory, it can be changed in the application settings
   files = os.listdir ("mysite / commands")
   modules = filter (lambda x: x.endswith ('. py'), files)
   for m in modules:
       importlib.import_module ("commands." + m [0: -3])

def get_answer (body):
    # Default message if unrecognizable
    message = "Sorry, I don't understand you. Write '/ help' to see my commands."
    attachment = ''
    for c in command_list:
        if body in c.keys:
            message, attachment = c.process ()
    return message, attachment

def create_answer (data, token):
   load_modules ()
   user_id = data ['from_id']
   message, attachment = get_answer (data ['text']. lower ())
   vkapi.send_message (user_id, token, message, attachment)

我的英语说得不好,所以我为歪曲的翻译道歉)

【问题讨论】:

    标签: python python-3.x bots chatbot vk


    【解决方案1】:

    使用 Peer_id,而不是 from_id。 (数据->对象->peer_id) (我使用了 php,但我遇到了类似的问题。这就是解决方案) 大概是这样的:

    def create_answer (data, token):
       load_modules ()
       user_id = data ['peer_id'] # id source edited
       message, attachment = get_answer (data ['text']. lower ())
       vkapi.send_message (user_id, token, message, attachment)
    

    from_id - 发送消息的人

    peer_id - 收到交易者消息的位置。 (对于组,它看起来像 20000005) 所以,你会将消息发送到对话(不管是这个 PM 还是与很多人的对话)

    【讨论】:

    • 请在您的答案中应用正确的文本/代码格式。
    猜你喜欢
    • 2019-06-27
    • 2018-11-19
    • 1970-01-01
    • 2022-11-11
    • 2012-09-21
    • 1970-01-01
    • 2019-04-01
    • 2019-11-19
    • 2021-05-13
    相关资源
    最近更新 更多