VK机器人通过私人消息而不是对话来回答

时间:2020-08-01 08:07:33

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

我正在创建一个引用机器人,用于使用Callback Api在Python中的VK中聊天。如果您写入群组消息,则该漫游器可以正常工作。但是,如果您写入对话(已向该机器人添加了对话),则会回复私人消息。授予阅读等所有权利。据我了解(在互联网上学习信息),我使用user_id,而不是chat_id。但是我不明白如何正确修复它(

p.s。明智的是,该漫游器会根据他们的要求在私人消息和对话中进行书写。

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)

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

1 个答案:

答案 0 :(得分:0)

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

class MainActivity : AppCompatActivity() {
    private val TAG = "TEST"
    private val FOREGROUND_LOCATION_CODE = 2

    // The BroadcastReceiver used to listen from broadcasts from the service.
    private var myReceiver: MyReceiver? = null

    // A reference to the service used to get location updates.
    private var mService: LocationService? = null

    // Monitors the state of the connection to the service.
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val binder: LocationService.LocalBinder = service as LocationService.LocalBinder
            mService = binder.service
        }

        override fun onServiceDisconnected(name: ComponentName) {
            mService = null
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        checkForegroundLocationPermission()

        myReceiver = MyReceiver()

        myReceiver?.let {
            LocalBroadcastManager.getInstance(this)
                .registerReceiver(it, IntentFilter(LocationService.ACTION_BROADCAST))
        }

        findViewById<Button>(R.id.start).setOnClickListener { view ->
            Snackbar.make(view, "Start listening...", Snackbar.LENGTH_LONG).show()

            Log.d("TEST", "Start listening...")

            mService?.requestLocationUpdates();
        }

        findViewById<Button>(R.id.stop).setOnClickListener { view ->
            Snackbar.make(view, "Stop listening...", Snackbar.LENGTH_LONG).show()

            Log.d("TEST", "Stop listening...")

            mService?.removeLocationUpdates()
        }
    }

    override fun onStart() {
        super.onStart()

        // Bind to the service. If the service is in foreground mode, this signals to the service
        // that since this activity is in the foreground, the service can exit foreground mode.
        // Bind to the service. If the service is in foreground mode, this signals to the service
        // that since this activity is in the foreground, the service can exit foreground mode.
        Intent(this, LocationService::class.java).also {
            bindService(it, mServiceConnection, BIND_AUTO_CREATE)
        }
    }

    override fun onResume() {
        super.onResume()

        Log.d(TAG, "onResume")
    }

    override fun onStop() {
        Log.d(TAG, "onStop")

        super.onStop()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun checkForegroundLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Check if permission is not granted
            Log.d(TAG, "Permission for foreground location is not granted")

            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                FOREGROUND_LOCATION_CODE)
        } else {
            // Permission is already granted, do your magic here!
            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show()
        }
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<out String>,
                                            grantResults: IntArray) {
        when (requestCode) {
            FOREGROUND_LOCATION_CODE -> {
                Log.d(TAG, "onRequestPermissionsResult ->  FOREGROUND_LOCATION_CODE")
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Foreground Permission granted", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Foreground Permission denied", Toast.LENGTH_SHORT).show()
                }

                return
            }
        }
    }

    private class MyReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val location: Location? = intent.getParcelableExtra(LocationService.EXTRA_LOCATION)
            if (location != null) {
                Log.d("TEST", "Location = $location")
            }
        }
    }
}

from_id - 发送消息的人

peer_id - 在其中接收到交易消息。 (对于组,它看起来像 20000005) 所以,你将消息发送到对话(不管是这个 PM 还是和很多人的对话)