(Python bot) How do I tag people in a conversation via a bot?
I have an interesting question. I have a bot on vk (written in Python). How to make it so that it can mark the participants of the conversation with a certain symbol through the loop? For example, how can you do this in the vk @id and the person is marked and he received a notification. Only I need the bot to write the characters $ $ $ $ $ $ $ $ and each character $ marks the person in the conversation. There is no way to do it manually, since you will have to open the code all the time and add a new person.
Here is my code
import vk_api
import random
import time
vk = vk_api.VkApi(token="021cad5014bf87033caafb6f6b3583a01018dbf391a48f05ea92a5b37e710c897d44278e13f66af7a1381")
app = Flask(__name__)
@app.route('/', methods = ["POST"])
def main():
data = json.loads(request.data)
if data["type"] == "confirmation":
return "0f05cbd9"
elif data["type"] == "message_new":
object = data["object"]
id = object["peer_id"]
body = object["text"]
if ("крут" in body.lower() or "cool" in body.lower()) and "полностью согласен! реально круто " != body.lower():
vk.method("messages.send", {"peer_id": id, "message": "О да, это точно круто! ", "random_id": random.randint(1, 2147483647)})
elif "привет" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Привет! Как жизнь?", "random_id": random.randint(1, 2147483647)})
elif "как дела" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "У меня все круто! Надеюсь у тебя также.", "random_id": random.randint(1, 2147483647)})
elif "начать" == body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Ну шо, погнали. Команды гадай сам или спроси у Санчая.", "random_id": random.randint(1, 2147483647)})
elif body.lower() == "бот, ссылку":
vk.method("messages.send", {"peer_id": id, "message": "Бро, подпишись vk.com/sanchbot", "random_id": random.randint(1, 2147483647)})
elif "ватафак" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Ват ю сей, мен! Ватафак!", "random_id": random.randint(1, 2147483647)})
elif body.lower() == "тиха":
vk.method("messages.send", {"peer_id": id, "message": "Тсссссссссссс!", "random_id": random.randint(1, 2147483647)})
elif "флекс" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "О да! ФЛЕКСИМ! ", "random_id": random.randint(1, 2147483647)})
elif "яратам" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Мин сине яратам! ❤", "random_id": random.randint(1, 2147483647)})
elif "татмак" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Мммм.. Татмаки, Родя сказал они вкусные", "random_id": random.randint(1, 2147483647)})
elif "добрый вечер" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Добрейший вечерочек ", "random_id": random.randint(1, 2147483647)})
elif "доброе утро" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Добрейшее утречко, господа ", "random_id": random.randint(1, 2147483647)})
elif "добрый день" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Добрый день, сэр! ", "random_id": random.randint(1, 2147483647)})
elif body.lower() == "бот, поздоровайся":
vk.method("messages.send", {"peer_id": id, "message": "Экии привет", "random_id": random.randint(1, 2147483647)})
elif "что мне сегодня приготовить" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Можешь приготовить мое сердечко ❤", "random_id": random.randint(1, 2147483647)})
elif "нарут" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Наруто - это круто!", "random_id": random.randint(1, 2147483647)})
elif "надевай очки" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "", "random_id": random.randint(1, 2147483647)})
elif "good morning" in body.lower() or "гуд монинг" in body.lower() or "гуд морнинг" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Доброе утро! Хорошего вам дня ❤", "random_id": random.randint(1, 2147483647)})
elif "доброй ночи" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Сладких снов ❤", "random_id": random.randint(1, 2147483647)})
elif "всем хорошего дня" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "И тебе хорошего дня!", "random_id": random.randint(1, 2147483647)})
elif "ех" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Еех!", "random_id": random.randint(1, 2147483647)})
elif "я ною" in body.lower():
vk.method("messages.send", {"peer_id": id, "message": "Вот именно! Че ты ноешь?!", "random_id": random.randint(1, 2147483647)})
return "ok"
1 answers
For a mention, you need to send a message like [id123456789|текст]
, where 123456789
is the id
of the user, and текст
is the text of the mention.
In order to get id
all the users of the conversation, you can send a request to vk API
, namely to the getConversationMembers
method. Keep in mind that the bot needs conversation admin rights.
I also allowed myself to exclude participants with a negative id
. This id
is the case for communities, that is, for our community and others bots.
Example:
from vk_api import VkApi
from vk_api.utils import get_random_id
import settings
vkBotSession = VkApi(token=settings.accessToken)
vk = vkBotSession.get_api()
def main():
members = vk.messages.getConversationMembers(
peer_id=2000000000,
)['items']
members_ids = [member['member_id'] for member in members if member['member_id'] > 0]
message = ''
for member_id in members_ids:
message += f'[id{member_id}|#]'
vk.messages.send(
peer_id=2000000000,
message=message,
random_id=get_random_id()
)
if __name__ == '__main__':
main()
In settings.py
I have the tokens. Replace it with your own. You should also replace all peer_id
in the code with peer_id
specifically for your conversation.
Well, I don't know why, the VK doesn't want to format the mention with the $
sign (although the notification comes), so I replaced the sign with #
.
UPD:
In order to get peer_id
, I use this script:
from vk_api import VkApi
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import settings # В этом файле у меня токены
vkSession = VkApi(token=settings.accessToken)
longPoll = VkBotLongPoll(vkSession, settings.groupId)
vk = vkSession.get_api()
def main() -> None:
for event in longPoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW:
print(event.obj['peer_id'])
if __name__ == '__main__':
main()
All that is required - send a message in a conversation with the bot.