Having error "got an unexpected keyword argument" and can't fix it - telegram-bot

Good day to everyone, I have been writing a simple bot to delete messages from one group and to forward them to another, so while executing I am facing this error, it says "TeleBot.forward_message() got an unexpected keyword argument 'chatid'"
I am new to bot making so any help would be appreciated
Here is my code
import telebot
from telebot import types
bot = telebot.TeleBot('tocken')
#bot.message_handler(commands=['start'])
def start(message):
bot.send_message(message.chat.id, 'Hi, ready to delete')
if ':' not in message.text:
bot.forward_message(chatid='group chat id',
fromchatid=message.chat.id, messageid=message.message_id)
bot.delete_message(chatid=message.chat.id, messageid=message.message_id)
bot.polling(none_stop=True)

It seems like you may be missmatching the variable's nomenclature.
Based on PyTelegramBot documentation, forward_message() expects this params:
forward_message(chat_id: Union[int, str], from_chat_id: Union[int,
str], message_id: int, disable_notification: Optional[bool] = None,
protect_content: Optional[bool] = None, timeout: Optional[int] = None,
message_thread_id: Optional[int] = None)
So your chatid should go like chat_id and the same goes with every other param.
Your snippet would go something like this:
bot.forward_message(chat_id='group chat id', from_chat_id=message.chat.id, message_id=message.message_id)
bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
Note: This nomenclature may be version dependant and was described as current latest (4.9.0).

Related

Telegram Global Search using the raw API function via Telethon

I am trying to use the SearchGlobalRequest API method for global, full-text search on Telegram, but I am not sure what to use for some of the arguments, especially the offset_peer parameter. When I do this:
try:
result = client(SearchGlobalRequest(
q=search_term,
filter=None,
min_date=datetime.datetime.strptime(min_date, '%Y-%m-%d'),
max_date=datetime.datetime.strptime(max_date, '%Y-%m-%d'),
offset_rate=-1,
# offset_peer=None,
offset_id=-1,
limit=10
))
except Exception as e:
print(e)
I get __init__() missing 1 required positional argument: 'offset_peer'.
When I try to pass None as offset_peer, I get Cannot cast NoneType to any kind of Peer. I am not trying to search in any specific channel, I just want to specify the start and end date and find all (or rather as many as possible) matching results.
I am using Telethon version 1.24.0.
Next code works for me:
from telethon.tl.functions.messages import SearchGlobalRequest
from telethon.tl.types import InputMessagesFilterEmpty, InputPeerEmpty
results = client(SearchGlobalRequest(
q='your_query_here',
filter=InputMessagesFilterEmpty(),
min_date=None,
max_date=None,
offset_rate=0,
offset_peer=InputPeerEmpty(),
offset_id=0,
limit=100,
folder_id=None
))
print(results.stringify())

make-basic.publish with default value for exchange gives exception error: bad argument

I'm trying to follow the RabbitMq hello world tutorial in Lisp Flavoured Erlang. The tutorial is for Elixir, with the help of Erlang RabbitMQ client user guide I try to translate the steps to LFE. To publish a message, I need a basic.publish-record.
When I try:
(make-basic.publish routing_key #"hello")
(in a function in my lfe-file, which I call from the REPL).
This results in:
** exception error: bad argument
in min_make_record:not-working-queue-declare/0 (/home/.../min_make_record/_build/default/lib/amqp_client/include/amqp_client.hrl, line 26)
When I call make-basic.publish with the same arguments from the REPL, it returns the record as expected.
The error appears to be related to the default argument for exchange. The record is defined in rabbit_common/include/rabbit_framing.hrl as:
-record('basic.publish', {ticket = 0, exchange = <<"">>, routing_key = <<"">>, mandatory = false, immediate = false}).
The following do work:
make-basic.publish from the REPL
passing an argument for both exchange and routing_key:
(make-basic.publish exchange #"" routing_key #"hello")
Removing exchange and routing_key from the record (or a copy of it) and then calling make-basic.publish
(make-amqp_params_network) from amqp_client.hrl this record also has binary strings with defaults:
-record(amq_params_network, {username = <<"guest">>, password=<<"guest">>, virual_host=<<"/">>, host="localhost", port=undefined, channel_max=2047, frame_max=0, heartbeat=10, connection_timeout=60000, ssl_options=none, auth_mechanisms=[fun amqp_auth_mechanisms:plain/3, fun amqp_auth_mechanisms:amqplain/3], client_properties = []¸socjet_options=[]}).
Is there a difference in the syntactic sugar LFE generates for direct includes and transitive includes?
Or does the point in the name cause problems?
I tried:
starting amqp_client (via .app.src): amqp_client must be started otherwise there is an other error.
including both amqp_client.hrl and rabbit_framing.hrl from my lfe-file: this results in lots of "record ... already defined"-errors.
(Adding an include guard to rabbit_framing.hrl does not help)

Celery Error Handling

I've built a fairly simple application linking Flask, Celery, and RabbitMQ using docker-compose by linking together a few solutions I saw online. I'm having some issues trying to update task states to reflect if a failure occurred. To keep error visibility at it's highest, I've had my custom class only raise expected errors, else the errors are handled at the celery app level as follows (in celery_app.py):
#celery_app.task(name='celery_worker.summary')
def async_summary(data):
"""Background summary processing"""
try:
logger.info('Summarizing text')
return BdsSummary(data, nlp=en_nlp).create_summary()
except Exception as e:
current_task.update_state(state='FAILURE', meta={'error_message': str(traceback.format_exc())})
logger.exception('Text Summary worker raised: %r'%e)
I've been doing some negative testing against my application, and when I pass it data that I know will throw an error (non-text data, for example), when i run r = requests.get('http://my.app.addr:8888/task/my-task-id') I get {'status': 'SUCCESS', 'result': None}. I'm vexed as to why this is happening. Based on my admittedly limited understanding of Celery's behavior, it should update the status to show a traceback and ExceptionClass, why would it not do this?
I am relatively new to Celery, so my understanding of the Canvas that they reference in the documentation is extremely basic. I'm just trying to provide some basic task failure information to the response/task. For context, when I give it proper input, I get back {'status': 'SUCCESS', 'result': {'summary': 'My Summary text here', 'num_sentences': 3, ...}}.
Any insight here would be much appreciated

Network Steganography StegoSip Tool

I am trying to use StegoSip tool coupled with Ekiga softphone. Finally Ekiga works, but when I run StegoSip, it gives me the warning that cb() takes exactly 3 arguments (2 given).
I found the function in the code and my opinion is that stegoSip does not recognize my conversation ( third argument ). I check the port and everything looks ok (SIP uses 5060 port).
I understand that the question is details, but I wasted too much time trying to fix this and I am desperate.
StegoSIP https://github.com/epinna/Stegosip
The problematic code:
def cb(self,i,nf_payload):
"""
Callback function of packet processing.
Get corresponding dissector and direction of packets with .getLoadedDissectorByMarker()
and send to the correct dissector using checkPkt() and processPkt().
"""
data = nf_payload.get_data()
pkt = stegoIP(data)
marker = nf_payload.get_nfmark()
dissector, incoming = dissector_dict.dissd.getLoadedDissectorByMarker(marker)
pkt.incoming = incoming
if not dissector:
nf_payload.set_verdict(nfqueue.NF_ACCEPT)
else:
dissector.checkPkt(pkt)
if pkt.extracted_payload:
dissector.processPkt(pkt, nf_payload)
return 1
The output is:
TypeError: cb() takes exactly 3 parameters (2 given)
Callback failure!

Twisted IRC Bot connection lost repeatedly to localhost

I am trying to implement an IRC Bot on a local server. The bot that I am using is identical to the one found at Eric Florenzano's Blog. This is the simplified code (which should run)
import sys
import re
from twisted.internet import reactor
from twisted.words.protocols import irc
from twisted.internet import protocol
class MomBot(irc.IRCClient):
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
print "attempting to sign on"
self.join(self.factory.channel)
print "Signed on as %s." % (self.nickname,)
def joined(self, channel):
print "attempting to join"
print "Joined %s." % (channel,)
def privmsg(self, user, channel, msg):
if not user:
return
if self.nickname in msg:
msg = re.compile(self.nickname + "[:,]* ?", re.I).sub('', msg)
prefix = "%s: " % (user.split('!', 1)[0], )
else:
prefix = ''
self.msg(self.factory.channel, prefix + "hello there")
class MomBotFactory(protocol.ClientFactory):
protocol = MomBot
def __init__(self, channel, nickname='YourMomDotCom', chain_length=3,
chattiness=1.0, max_words=10000):
self.channel = channel
self.nickname = nickname
self.chain_length = chain_length
self.chattiness = chattiness
self.max_words = max_words
def startedConnecting(self, connector):
print "started connecting on {0}:{1}"
.format(str(connector.host),str(connector.port))
def clientConnectionLost(self, connector, reason):
print "Lost connection (%s), reconnecting." % (reason,)
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "Could not connect: %s" % (reason,)
if __name__ == "__main__":
chan = sys.argv[1]
reactor.connectTCP("localhost", 6667, MomBotFactory('#' + chan,
'YourMomDotCom', 2, chattiness=0.05))
reactor.run()
I added the startedConnection method in the client factory, which it is reaching and printing out the proper address:host. It then disconnects and enters the clientConnectionLost and prints the error:
Lost connection ([Failure instance: Traceback (failure with no frames):
<class 'twisted.internet.error.ConnectionDone'>: Connection was closed cleanly.
]), reconnecting.
If working properly it should log into the appropriate channel, specified as the first arg in the command (e.g. python module2.py botwar. would be channel #botwar.). It should respond with "hello there" if any one in the channel sends anything.
I have NGIRC running on the server, and it works if I connect from mIRC or any other IRC client.
I am unable to find a resolution as to why it is continually disconnecting. Any help on why would be greatly appreciated. Thank you!
One thing you may want to do is make sure you will see any error output produced by the server when your bot connects to it. My hunch is that the problem has something to do with authentication, or perhaps an unexpected difference in how ngirc handles one of the login/authentication commands used by IRCClient.
One approach that almost always applies is to capture a traffic log. Use a tool like tcpdump or wireshark.
Another approach you can try is to enable logging inside the Twisted application itself. Use twisted.protocols.policies.TrafficLoggingFactory for this:
from twisted.protocols.policies import TrafficLoggingFactory
appFactory = MomBotFactory(...)
logFactory = TrafficLoggingFactory(appFactory, "irc-")
reactor.connectTCP(..., logFactory)
This will log output to files starting with "irc-" (a different file for each connection).
You can also hook directly into your protocol implementation, at any one of several levels. For example, to display any bytes received at all:
class MomBot(irc.IRCClient):
def dataReceived(self, bytes):
print "Got", repr(bytes)
# Make sure to up-call - otherwise all of the IRC logic is disabled!
return irc.IRCClient.dataReceived(self, bytes)
With one of those approaches in place, hopefully you'll see something like:
:irc.example.net 451 * :Connection not registered
which I think means... you need to authenticate? Even if you see something else, hopefully this will help you narrow in more closely on the precise cause of the connection being closed.
Also, you can use tcpdump or wireshark to capture the traffic log between ngirc and one of the working IRC clients (eg mIRC) and then compare the two logs. Whatever different commands mIRC is sending should make it clear what changes you need to make to your bot.