I have recently created a simple bot for telegram using the pyTelegramBotAPI (telebot).
I added a message handler that is supposed to handle every message, including the ones that appear on a group when a new user joins, which are still Message objects a non-null new_chat_members property.
import telebot
bot = telebot.TeleBot(TOKEN)
[...]
#bot.message_handler(func=lambda m: True)
def foo(message):
bot.send_message(message.chat.id,"I got the message")
bot.polling()
Even so, the bot does not reply with the "I got the message" string when I add a new user, although it does catch other messages.
Why is this happening? Is this a problem about the message handler? Is there maybe a more general handler that is sure to catch every update?
Thank you
you should specify "new_chat_members" as content-types.
Here is a sample working snippet that welcomes new users:
import telebot
bot = telebot.TeleBot(TOKEN)
#bot.message_handler(content_types=[
"new_chat_members"
])
def foo(message):
bot.reply_to(message, "welcome")
bot.polling()
Related
I'm trying to send welcome message to newcomers to the channel via the bot using Aiogram. However, my bot can't find the chat with the user if he has not started a conversation with the bot before. Are there any solutions of this problem?
I have already managed to handle newcomers and add ids to the db, but
`
#router.chat_member(ChatMemberUpdatedFilter(member_status_changed=(KICKED | LEFT | RESTRICTED)
>>
(ADMINISTRATOR | CREATOR | MEMBER)))
async def on_user_join(event: ChatMemberUpdated):
with grpc.insecure_channel('') as channel:
stub = sub_unsub_pb2_grpc.SubscribtionServiceStub(channel)
timestamp = timestamp_pb2.Timestamp()
timestamp.FromDatetime(datetime.now(tz=timezone.utc))
request = sub_unsub_pb2.SubUnsubEvent(
id=str(event.new_chat_member.user.id),
channelId=str(event.chat.id),
time=timestamp,
subStatus='join'
)
response = sub_unsub_pb2.EventResponse()
stub.TriggerEvent(request)
`
But when I try to send a message, the error chat not found is thrown.
`
await support_bot.send_message(
user_id,
f'Welcome to the channel!'
)
`
Solutions to this problem:
Is to have the bot transfer a message to the user as soon as their ID
is added to the database. This way, the user will have started a
discussion with the bot, and the bot will be capable of finding the
chat when you try to send the welcome message.
Is to use the start command, so that new users can initiate the
discussion with the bot by sending /start command. Also, in the
start command handler, you can check whether the user is a new member
and send a welcome message.
Check the user's presence in the channel by using the
get_chat_member method of the bot, which returns a ChatMember
object. If the status attribute of this object
isChatMember.CHAT_MEMBER_STATUS_LEFT, then the user isn't a member
of the channel anymore and you shouldn't send the message.
Use the message event to listen for all messages transferred by the
user in the channel and check if the user is new or not and send the
welcome message accordingly
I'm using Telebot to build a simple Telegram bot. I've set up a message handler that responds to commands succesfully, but when I try to send a single message I get an error if I use the chat id (ex: 1234567890):
Error code: 403. Description: Forbidden: bot can't send messages to
bots
I get a different error when I use the user id (ex: #my_user):
Error code: 400. Description: Bad Request: chat not found
This is my code, the auth is correct:
tg_bot = telebot.TeleBot(TG_TOKEN, parse_mode='MARKDOWN')
tg_bot.send_message(chat_id=CHAT_ID_USER, text="hola test")
Is the bot's chat different to the chat I'm supposed to talk with? Any solution and details about the bot functionality will be apreciated, I'm still learning about that!
try this
import telebot
bot = telebot.TeleBot(token)
#bot.message_handler(commands=['start'])
def start(message):
bot.send_message("1395609507","Hello")
bot.infinity_polling()
If the user under this id has not started your bot, then the bot will not be able to write to him/her first. And in this case it is natural to get the error "chat not found". This error can also be observed when working with users who first used the bot and then blocked it.
I'm creating a simple Twitch bot for personal use. I'm using twitchio.ext commands. Everything works fine, I'm connected, I'm able to print all the messages from the chat, my bot responds to commands but I'm not able to send a message to chat and I don't know why.
from twitchio.ext import commands
class Bot(commands.Bot):
def __init__(self):
super().__init__(token='oauth:censored', prefix='g ', nick = "nick of the bot", irc_token = "censored", initial_channels=['channel'])
async def event_ready(self):
print(f'Using bot as {self.nick}')
#commands.command()
async def test(self, ctx: commands.Context):
await ctx.send('test')
print("printed")
bot = Bot()
#bot.event()
async def event_message(msg):
print(msg.author.name)
print(msg.content)
await bot.handle_commands(msg)
bot.run()
When I type "g test" in chat, the message "test" is not sent but the message "printed" is printed to the console. Do you know where could be the problem? Also, I would like to ask if there is any way how to send a message to chat directly without responding to a command or event.
Try adding the bot as a mod
The 'nick' in the bot init() function doesn't seem to do anything the nick is linked to your IRC username.
I'm assuming the channel in your initial_channels in the init() func isn't actually the channel you put there since you said you were able to type in the chat.
If the channel that you are using the bot from(linked to the oauth key) is not the same channel as you are connecting to in the chat then you probably need to add the bots username as a moderator in that chat
try
/mod [bot_username]
in the chat as the channel owner to do this
Also if your bot is the same account you are sending commands from on twitch the rate limit will be reached unless they are a mod. So either make a dedicated account for your bot or mod the bot on the server
import discord
from discord.ext import commands
async def anyfunc(ctx):
await ctx.send(f"{ctx.message.author.mention}, "Hi!")
bot_message_id = ((bot's_last_message)).id
What to put in (()) to make the bot remember the id of the message that it will send?
Is there a way to take the id of the next (for example, user's) message (that hasn't been sent yet) as a variable?
ctx.send() returns the discord.Message instance of the message it sent, so you can store it in a variable.
message = await ctx.send(f"{ctx.message.author.mention}, Hi!")
# do what you want with the message, in your case getting it's id
bot_message_id = message.id
As for your second question, if you want to get the response of a user to that message (so the next message a specific user will send), you can use the built-in wait_for for this.
def check(message):
return message.author.id == the_id_of_that_user
message = await bot.wait_for("message", check=check)
That way, the bot will literally wait for a message that makes your check function return True, or in this case a message sent by that very user. More info on that in the relevant API documentation.
I couldn't understand your question very good but I'll try to answer. according to API References you can get someone's last message with using channel.history().get(). So here is a example:
import discord
from discord.ext import commands
async def anyfunc(ctx):
await ctx.send(f"{ctx.message.author.mention}, Hi!")
bot_message_id = await ctx.channel.history().get(author__name="Bot's name").id
This will probably work but in case of error, maybe you can try author__id=bot's id instead of author__name.
I want to send message to dms using my discord bot and because the api has changed from client.send_message(user, message) to channel.send(message) I have no idea how to do that, also I dont want to make it dependent on the on_message(message) event. Any ideas?
If you have the user ID you can do:
user = client.get_user(user_id)
await user.send('Hello')
However If you already have the User object, you can do the following:
await message.author.send('Hey')
Where message is a Message object received from a on_message() event.
As for whether you can send private messages without first receiving an event unfortunately that is not be possible due to obvious spam-related issues.