I have been building a Discord bot, which will send messages to selected channels in servers on a change in the database, specifically if a new document is inserted. I am using MongoDB as the database, I came to know about collection.watch() in pymongo. I wrote the code for watch() in db.py as given in the pymongo documentation. "hackathons" here is the collection on which the watch method is applied.
def new_hackathon():
try:
resume_token = None
pipeline = [{'$match':{'operationType':'insert'}}]
with hackathons.watch(pipeline) as stream:
for change in stream:
print(change)
resume_token = stream.resume_token
except pymongo.errors.PyMongoError:
if resume_token is None:
logging.error('...')
else:
with hackathons.watch(pipeline, resume_after=resume_token) as stream:
for change in stream:
print(change)
I have called the new_hackathon() function in another file.
class Channels(commands.Cog):
#class methods
new_hackathon()
def setup(bot):
bot.add_cog(Channels(bot))
The call to new_hackathon() function does not lets the cog load, thus no response is given by the bot. If the function is not called the bot works perfectly.
Well the good news is that I ran your code and I can see the change streams coming through. So that's a good start.
I would therefore get you to double check the connection string, database and collection parameters are all set correctly.
One of the issues with change streams is that if you have these configured incorrectly it will happily just sit there doing nothing ...