Conky/ヒントとテクニック

提供: ArchWiki
2024年4月18日 (木) 22:30時点におけるKgx (トーク | 投稿記録)による版 (→‎Display a calendar for the current month: 翻訳)
ナビゲーションに移動 検索に移動

関連記事

パッケージのアップデート情報を表示する

pacman-contrib は、公式リポジトリからのパッケージの更新を表示する checkupdates というスクリプトを提供します。${execi 3600 checkupdates | wc -l} を実行すると、パッケージの総数が表示されます。

テキストファイルの末尾を表示

conky は、conky(1) § tail ファイルをデスクトップにすることができます。これは主にテキストファイルに役立ちます。たとえば、/var/log/ ファイルを読み取り、あらゆる種類のログメッセージを表示します。これらのファイルのほとんどは root によってのみ読み取ることができますが、conkyroot として実行することは推奨されないため、に自分自身を log ユーザーグループ に追加する必要があります。さらに、systemd ログファイルはバイナリファイルであるため、この機能は以前よりも役に立ちません。 ただし、lua スクリプトを使用して実現できます。

天気予報を表示する

これは、外部 Web ページ (通常は天気予報専用のページ) を読み取ることで実現されます。このスレッド を参照してください。lua の別の天気スクリプト: ここ

カウントダウンタイマーを表示する

ConkyTimer は作業の残り時間を表示するシンプルなカウントダウンタイマーです。

conkytimer "<task description>" <min> でタイマーを開始できます。

RSS フィードを表示

外部のスクリプトを実行したり Conky に出力したりすることなく、RSS フィードをネイティブに表示する機能が Conky には備わっています。例えば、Planet Arch の最新の記事のタイトル10件を表示して毎分ごとにフィードを更新したい場合、以下を conky.confTEXT セクションに挿入します:

${rss https://planet.archlinux.org/rss20.xml 300 item_titles 10 }

Arch フォーラムの rss フィードを表示したい場合、次の行を追加します:

${rss https://bbs.archlinux.org/extern.php?action=feed&type=rss 300 item_titles 4}

300 は更新間隔で (15分がデフォルト)、4 は表示するアイテムの数です。

当月のカレンダーを表示します

次の lua スクリプトを使用してカレンダーを表示できます。color1 と設定のデフォルトの色が使用されます。等幅フォントを使用するのが最適です。

 #!/usr/bin/env lua
 
 conky_color = "${color1}%2d${color}"
 
 t = os.date('*t', os.time())
 year, month, currentday = t.year, t.month, t.day
 
 daystart = os.date("*t",os.time{year=year,month=month,day=01}).wday
 
 month_name = os.date("%B")
 
 days_in_month = {
     31, 28, 31, 30, 31, 30, 
     31, 31, 30, 31, 30, 31
 }
 
 -- check for leap year
 -- Any year that is evenly divisible by 4 is a leap year
 -- Any year that is evenly divisible by 100 is a leap year if
 -- it is also evenly divisible by 400.
 LeapYear = function (year)
     return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
 end
 
 if LeapYear(year) then
     days_in_month[2] = 29
 end
 
 title_start = (20 - (string.len(month_name) + 5)) / 2
 
 title = string.rep(" ", math.floor(title_start+0.5)) .. -- add padding to center the title
         (" %s %s\n Su Mo Tu We Th Fr Sa\n"):format(month_name, year)
 
 io.write(title)
 
 function seq(a,b)
     if a > b then
         return
     else
         return a, seq(a+1,b)
     end 
 end
 
 days = days_in_month[month]
 
 io.write(
     string.format(
         string.rep("   ", daystart-1) ..
         string.rep(" %2d", days), seq(1,days)
     ):gsub(string.rep(".",21),"%0\n")
      :gsub(("%2d"):format(currentday),
            (conky_color):format(currentday)
      ) .. "\n"
 )

conky.conf 内に以下を配置し、パスがスクリプトを保存した場所と一致することを確認します。

 conky.text = [[
 ${execpi 3600 ~/.config/conky/cal.lua}
 ]]

Display rTorrent stats

See this thread.

Display your WordPress blog stats

This can be achieved by using the in python written extension named ConkyPress.

Display number of new emails

Conky has built in support for IMAP and POP3, but does not have support for access over ssl. Conky's FAQ recommends using stunnel for this and has an example configuration here.

Modify /etc/stunnel/stunnel.conf as follows, and then start stunnel.service:

  1. Service-level configuration for TLS server
[imap]
client = yes
accept  = 143
connect = imap.gmail.com:143
protocol = imap
sslVersion = TLSv1
# Service-level configuration for SSL server
[imaps]
client = yes
accept  = 993
connect = imap.gmail.com:993

Then add the following to conky.conf:

conky.config = {
    imap = "localhost username password [-i 120] [-f 'inbox'] [-p 993]",
}
conky.text {
    Inbox: ${imap_unseen}/${imap_messages}
}

Gmail

If you use 2-factor authentication, you need to use an App Password.

For method 1, 2 and 3:

Create one of the following files in a convenient location (for example in ~/.scripts/).

Then add the following string to your conky.conf in order the check your Gmail account for new email every five minutes (300 seconds) and display:

${execi 300 python ~/.scripts/gmail.py}

method 1

This script uses retrieves the number of new email via Gmail's Atom API.

gmail.py
#!/usr/bin/env python3

import urllib.request

email = 'your email'
password = 'your password'

# Set up authentication for gmail
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='mail.google.com',
                          uri='https://mail.google.com/',
                          user=email,
                          passwd=password)
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)

gmailurl = 'https://mail.google.com/gmail/feed/atom'
with urllib.request.urlopen(gmailurl) as page:
    contents = page.read().decode('utf-8')

ifrom = contents.index('<fullcount>') + 11
ito   = contents.index('</fullcount>')

fullcount = contents[ifrom:ito]

print('{} new emails'.format(fullcount))

method 2

Same as method 1, but does proper XML parsing.

gmail.py
#!/usr/bin/env python3

import urllib.request
from xml.etree import ElementTree as etree

email = 'your email'
password = 'your password'

# Set up authentication for gmail
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='mail.google.com',
                          uri='https://mail.google.com/',
                          user=email,
                          passwd=password)
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)

gmailurl = 'https://mail.google.com/gmail/feed/atom'
NS = '{http://purl.org/atom/ns#}'
with urllib.request.urlopen(gmailurl) as source:
    tree = etree.parse(source)
fullcount = tree.find(NS + 'fullcount').text

print('{} new emails'.format(fullcount))

method 3

The same way, but with using curl, grep and sed:

gmail.sh
#!/usr/bin/sh

curl -s -u email:password https://mail.google.com/mail/feed/atom | grep fullcount | sed 's/<[^0-9]*>//g'

replace email and password with your data.

IMAP + SSL using Perl

Conky has built in support for IMAP accounts but does not support SSL. This can be provided using this script from this forum post. This requires the Perl/CPAN Modules Mail::IMAPClient and IO::Socket::SSL which are in the perl-mail-imapclient and perl-io-socket-ssl packages

Create a file named imap.pl in a location to be read by conky (for example in ~/.scripts/). In this file, add (with the appropriate changes):

imap.pl
#!/usr/bin/perl
 
# by gxmsgx
# description: get the count of unread messages on imap

use strict;
use Mail::IMAPClient;
use IO::Socket::SSL;

my $username = 'example.username'; 
my $password = 'password123'; 

my $socket = IO::Socket::SSL->new(
  PeerAddr => 'imap.server',
  PeerPort => 993
 )
 or die "socket(): $@";
 
my $client = Mail::IMAPClient->new(
  Socket   => $socket,
  User     => $username,
  Password => $password,
 )
 or die "new(): $@";
 
if ($client->IsAuthenticated()) {
  my $msgct;

  $client->select("INBOX");
  $msgct = $client->unseen_count||'0';
  print "$msgct\n";
}

$client->logout();

Add to conky.conf:

${execi 300 ~/.scripts/imap.pl} 

or wherever you saved the file.

If you use Gmail you might need to generate an application specific password.

Alternatively, you can use stunnel as shown above: #Gmail

IMAP using PHP

Another alternative using PHP. PHP needs to be installed and extension=imap must be uncommented in /etc/php/php.ini.

Then create a file named imap.php in a location to be read by conky (for example in ~/.scripts/). Make the file executable.

In this file, add (with the appropriate changes):

imap.php
#!/usr/bin/php
<?php
// See http://php.net/manual/function.imap-open.php for more information about
// the mailbox string in the first parameter of imap_open.
// This example is ready to use with Office 365 Exchange Mails,
// just replace your username (=email address) and the password.
$mbox = imap_open("{outlook.office365.com:993/imap/ssl/novalidate-cert}", "username", "password");

// Total number of emails
$nrTotal = imap_num_msg($mbox);
 
// Number of unseen emails. There are other ways using imap_status to count
// unseen messages, but they don't work with Office 365 Exchange. This one does.
$unseen = imap_search($mbox, 'UNSEEN');
$nrUnseen = $unseen ? count($unseen) : 0;
 
// Display the result, format as you like.
echo $nrUnseen.'/'.$nrTotal;
 
// Not needed, because the connection is closed after the script end.
// For the sake of clean public available scripts, we are nice to
// the imap server and close the connection manually.
imap_close($mbox);

Add to conky.conf:

${execi 300 ~/.scripts/imap.php} 

or wherever you saved the file.

This script displays A/B where A is the number of unseen emails and B is the total number of mails in the mailbox. There are a lot of other information available through a lot of PHP functions like with imap_Status (https://php.net/manual/function.imap-status.php). Just see the PHP docs about IMAP: https://php.net/manual/ref.imap.php.

Show graphic of active network interface

To test if a network inferface is currently active, you can use the test conky variable if_existing on the operstate of the interface. Here is an example for wlo1 :

draw_graph_borders yes 
${if_existing /sys/class/net/wlo1/operstate up}
${color #0077ff}Net Down:$color ${downspeed wlo1}      ${color #0077ff}Net Up:$color ${upspeed wlo1}
${color #0077ff}${downspeedgraph wlo1 32,155 104E8B 0077ff} $alignr${color #0077ff}${upspeedgraph wlo1 32,155 104E8B 0077ff}
${endif}

This is the expected result :

https://i.imgur.com/pQQbsP6.png

User-contributed configuration examples

  • A sample rings script with nvidia support - gist