Score:0

cronjob not working for daily messaging for slack

us flag

Ubuntu 20.04
python 3.8

I am trying to send a message to slack channel everyday at 9am using crontab.

Following https://www.youtube.com/watch?v=5bTkiV_Aadc&t=482s crontab successfully works when I write to log file every minute.

However replicating same method to slack messaging seems to not work and cannot find a reason for it.

Here is what I've tried out so far (reference: Why crontab scripts are not working?)

First, here is what my code looks like:

from dotenv import load_dotenv
import datetime
import numpy as np
import os
import pandas as pd
from pathlib import Path
import plotly.graph_objects as go
import slack

# ---- Commented out -----
# from extract_data import DataExtraction
# from const import inf_type, slack_channel
# env_path = Path('.') / '.env'
# load_dotenv(dotenv_path=env_path)
# --------------

date = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(dir_path, 'test_log.log')

# Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)

def write_to_log():
    logger.info("test")


if __name__ == "__main__":
    write_to_log()
  1. Above code works on crontab only if I comment out part when I am using environment variable or importing script that does.

  2. After checking it works for writing to log file, replacing writing to log to sending message to slack doesn't seem to work.

Here is replaced code (all the above code are the same)

def send_msg():
    client = slack.WebClient(token="Token_name")
    client.chat_postMessage(channel="#slackbot_test", text="helllo")

if __name__ == "__main__":
    send_msg()

Currently no luck in searching for if crontab does not work with slack, any help would be appreciated, thanks!

Score:0
it flag

Jobs run through cron, or systemd startup scripts aren't run in the same runtime environment that you have on your desktop. systemd startup scripts are run as root. None of your PATH changes, or other environment variable settings are automatically propagated to your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).

One can set environment variables for all one's cron jobs in the crontab file Read man 5 crontab.

Look at the results of echo "=== id ===";id;echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.

Since the command part of the crontab line is, by default, interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script (executable, mounted, starts with #!/bin/bash) which sets up the environment, then calls the desired program.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.